home *** CD-ROM | disk | FTP | other *** search
/ Info-Mac 1993 May / Info-Mac_II_May_1993.to_.sit / Info-Mac II (May 1993).toast / Unix / Maclayers-unix-side.shar < prev    next >
Internet Message Format  |  1993-03-27  |  137KB

  1. From: Eric Rosen <eric@cse.ucsc.edu>
  2. Date: Sun, 17 Jan 1993 23:12:39 -0800 
  3. Subject: comm/maclayers-unix-side.shar 
  4.  
  5.  
  6. # This is a shell archive.  Remove anything before this line,
  7. # then unpack it by saving it in a file and typing "sh file".
  8. #
  9. # Wrapped by  on Sun Jan 17 23:08:12 CST 1993
  10. # Contents:  layers_1.10/ layers_1.10/INFO layers_1.10/README
  11. #    layers_1.10/layers.1 layers_1.10/layers.c layers_1.10/layers.h
  12. #    layers_1.10/layersize.c layers_1.10/layertitle.c layers_1.10/macbput.1
  13. #    layers_1.10/macbput.c layers_1.10/macbput.h layers_1.10/makefile
  14. #    layers_1.10/protocol.c
  15.  
  16. echo mkdir - layers_1.10
  17. mkdir layers_1.10
  18. chmod u=rwx,g=rx,o=rx layers_1.10
  19.  
  20. echo x - layers_1.10/INFO
  21. sed 's/^@//' > "layers_1.10/INFO" <<'@//E*O*F layers_1.10/INFO//'
  22.  
  23.                              MacLayers 1.20
  24.                             January 16, 1993
  25.  
  26.  
  27.      MacLayers is a vt100 terminal emulator that allows multiple
  28.      terminal windows to be opened to a host simultaneously over a
  29.      single serial connection.  The remote host computer must be a
  30.      UNIX system which has sockets support. Each terminal window
  31.      may be associated with a shell, login to a different host, or
  32.      an individual command. Complete facilities are available for
  33.      controlling the window and the associated host processes attached
  34.      thereto.
  35.  
  36.      MacLayers is free for all to use, but is not in the public
  37.      domain.  You may not sell MacLayers or any program derived from
  38.      it.
  39.  
  40.      MacLayers is distributed in two parts, a Macintosh side and a
  41.      Unix side. Both are available via anonymous FTP from the official
  42.      MacLayers archive site, rascal.ics.utexas.edu, in mac/COMM/MacLayers.
  43.  
  44.  
  45.                        Quick Start for MacLayers Experts
  46.                        ---------------------------------
  47.  
  48.      Here is the minimum information that users of MacLayers 1.10 need
  49.      in order to upgrade.
  50.  
  51.      1.  You need to rebuild your startup (settings) files since the
  52.          format has changed.  Erratic behaviour may result from the
  53.          use of old settings files.
  54.  
  55.      2.  You need to install a new version of macbput on your UNIX host.
  56.  
  57.      3.  Other UNIX programs (layers, layersize, layertitle) need not be 
  58.          upgraded.
  59.  
  60. @//E*O*F layers_1.10/INFO//
  61. chmod u=rw,g=r,o=r layers_1.10/INFO
  62.  
  63. echo x - layers_1.10/README
  64. sed 's/^@//' > "layers_1.10/README" <<'@//E*O*F layers_1.10/README//'
  65.                                  MacLayers v1.20
  66.                            Unix-Side (layers) 1.20 Release
  67.                                 17 January, 1993
  68.  
  69. The following files are provided with the Unix side of the MacLayers v1.20
  70. release. 
  71.  
  72.     README        - this file
  73.  
  74.     layers.1    - layers command Unix manual page
  75.     makefile    - layers Makefile
  76.  
  77.     layers.c    - layers source files
  78.     layers.h
  79.     protocol.c
  80.     layersize.c
  81.     layertitle.c
  82.  
  83.     macbput.1    - v1.20 updated Unix manual page for macbput
  84.     macbput.c    - v1.20 updated source to macbput
  85.     macbput.h
  86.  
  87.                           Note: macbput is a public domain download utility;
  88.                                 the version distributed with layers v1.20
  89.                                 is intended for use only with MacLayers v1.20.
  90.  
  91. If you are upgrading from layers v1.10, note that no changes have been
  92. made to the layers, layertitle, and layersize programs. Only the program
  93. macbput and associated man page have changed. 
  94.  
  95.  
  96.  
  97.                          ***  SUPPORTED SYSTEMS  ***
  98.  
  99. MacLayers has been successfully installed on the following systems:
  100.  
  101.    SunOS 4.0.3
  102.    SunOS 3.2
  103.    Sequent DYNIX 3.0.12 (#DEFINE SEQUENT)
  104.    Sequent DYNIX 3.0.4  (#DEFINE SEQUENT)
  105.  
  106. MacLayers has failed to install on these systems:
  107.  
  108.    AIX 2.2.1 on IBM RT        Unsupported ioctls
  109.    IRIX 4.0.1 on 440VGX    
  110.  
  111.  
  112.                            ***   INSTALLATION   ***
  113.  
  114. There are three ways to install the layers system:
  115.  
  116.     make all
  117.  or
  118.     make installsetuid
  119.  or
  120.     make installnosetuid
  121.  
  122. Installing the layers utility setuid allows the layers command to perform
  123. two necessary actions as part of its operation.
  124.  
  125. First, if your system keeps /etc/utmp protected from general user access
  126. the setuid allows proper updating of /etc/utmp so that logons are properly 
  127. displayed by commands such as 'who'.  More importantly utilities like talk 
  128. and write will not function properly for layers users without the setuid 
  129. installation.
  130.  
  131. Second, setuid allows the layers utility to perform chown/chmod on its 
  132. allocated pseudo-ttys. This is necessary to plug security holes in some 
  133. systems which otherwise would allow outside users free access to the pseudo 
  134. control terminal ttys of layers users.
  135.  
  136. There are a few customizing parameters which may be of interest to system
  137. administrators near the beginning of file layers.c (especially for Sequent 
  138. systems.)
  139.  
  140.                          **** end of document ****
  141. @//E*O*F layers_1.10/README//
  142. chmod u=rw,g=r,o=r layers_1.10/README
  143.  
  144. echo x - layers_1.10/layers.1
  145. sed 's/^@//' > "layers_1.10/layers.1" <<'@//E*O*F layers_1.10/layers.1//'
  146. @.TH LAYERS l  "17 March 1990"
  147. @.SH NAME
  148. @.PP
  149. layers, layertitle \- Protocol for MacLayers Multiwindow Terminal Emulator for Unix
  150. @.SH SYNOPSIS
  151. layers                - start window protocol
  152. @.LP
  153. layers [-l] [command] - create new window
  154. @.LP
  155. layertitle string     - retitle current layers window
  156. @.IX  "layers" "start layers protocol, create new window"
  157. @.IX  "layertitle" "rename current layers window"
  158. @.SH DESCRIPTION
  159. @.PP
  160. MacLayers provides multi-window capability for a Macintosh (greater than 128K)
  161. connected to a host UNIX(TM) system with sockets support. Each window may be 
  162. associated with a shell, login to a different host, or an individual 
  163. command. Complete facilities are available for controlling the window 
  164. and the associated host processes attached thereto.
  165. @.PP
  166. To use MacLayers, you must have the MacLayers vt-100 terminal emulation
  167. program on a Macintosh and the layers protocol program installed on your
  168. Unix host.
  169. @.SH MACLAYERS OPERATION
  170. @.PP
  171. The Maclayers Application on the Mac starts up as a garden variety 
  172. host-to-terminal vt-100 emulator. (As such you can run it with any
  173. host, not just a Unix machine.) Baud rate and other configurations are set 
  174. by selections in the Control Menu.
  175. @.PP
  176. Enter the 
  177. @.I layers
  178. command to the Unix host using no options or parameters
  179. to start the layers protocol.  The initial terminal window will be closed
  180. and replaced with a layers protocol window.  A shell is run in this
  181. window, either /bin/sh or the shell indicated by your $SHELL variable.
  182. @.PP
  183. You can start a new shell layer by picking "New" on the Layers menu. You can
  184. also start a new layer window by issuing the
  185. @.I layers 
  186. command to a
  187. shell layer window. If you use no operands then the new layer window
  188. will be a shell. However, you can specify any command you wish by
  189. simply adding it as a parameter.  Examples: "layers vi testfile.c",
  190. "layers telnet earth."
  191. @.PP
  192. If you are specifying a shell then you can also elect to have it be a 
  193. login shell by adding a -l option. This allows broadcast/write/talk 
  194. capabilities for that window. The initial layer window shell defaults
  195. to a login shell.
  196. @.PP
  197. When a layer process group terminates its window is automatically closed.
  198. MacLayers exits layers mode when the last (or only) layer window is closed.
  199. You may also use the Layers Menu "Shutdown" to terminate layers mode.
  200. You cannot quit the MacLayers application while in layers mode but must 
  201. Shutdown the multi-window mode first.
  202. @.PP
  203. You can abort host 
  204. @.I layers
  205. by using the Control Menu "Abort Host Layers" 
  206. item which is always available. This may be necessary if your Mac 
  207. loses contact with the host and you restart the MacLayers application at
  208. which time the host would still be in multi-window layers mode while
  209. the application would not. If the MacLayers application terminates due
  210. to a non-recoverable problem it will always issue an order to terminate
  211. layers mode on the host before returning to the Finder.
  212. @.SH XMODEM DOWNLOADING
  213. @.PP
  214. MacLayers has a download facility for downloading XMODEM MacTerminal
  215. ('macput' command) and MacBinary ('macbput' command) files. Straight 
  216. vanilla XMODEM is not supported.
  217. Only one window can be doing a XMODEM download at any one time.
  218. Downloading does not effect any other MacLayers operations so you can
  219. freely use any other windows or applications (with MultiFinder) while 
  220. a download is in progress. Remember though that the topmost window 
  221. receives the highest priority data transfer from the host. So for the 
  222. fastest downloading keep the XMODEM layer window the active window.
  223. @.SH FILES
  224. @.PP
  225.  /usr/tmp/layers/<login>       Directory created by 
  226. @.I layers
  227.  /usr/tmp/layers/<login>/host.ttySocket Created by 
  228. @.I layers
  229. @.SH AUTHOR
  230. Dave Trissel
  231. @.SH BUGS AND CAVEATS
  232. @.PP
  233.  *) The shell TERM variable must have the same value in your 
  234. layer shells as it does when you initially start 
  235. @.I layers
  236. up.
  237. @.PP
  238.  *) If you set the BSD shell TERMCAP variable then that variable must
  239. be set in your .login file. It may not be changed to something
  240. different in .cshrc.
  241. @.PP
  242.  *) The 
  243. @.I layers
  244. command will not properly work when being issued from a
  245. remote login into the same machine which is already running the
  246. initial 
  247. @.I layers
  248. startup command.
  249. @.PP
  250.  *) There is no file upload facility.
  251. @.PP
  252.  *) MacLayers will access the disk less often if you have RAM Cache
  253. enabled on the Macintosh.
  254. @.PP
  255.  *)Layers must be installed as set-uid with owner root in order
  256. to  be  able to correctly change the owner of the tty device
  257. file for  each  window. Special  permission  may  also  be
  258. required to write the file "/etc/utmp".
  259. @.SH SEE ALSO
  260. @.PP
  261. The MacLayers program is
  262. completely described in the manual that accompanies it.
  263. @.PP
  264. Manual page courtesy of Peter Newton.
  265. @.PP
  266. UNIX(TM) is a registered trademark of American Telephone and Telegraph.
  267. Macintosh is a trademark of McIntosh Laboratories and is licensed to Apple 
  268. Computer.
  269. @//E*O*F layers_1.10/layers.1//
  270. chmod u=rw,g=r,o=r layers_1.10/layers.1
  271.  
  272. echo x - layers_1.10/layers.c
  273. sed 's/^@//' > "layers_1.10/layers.c" <<'@//E*O*F layers_1.10/layers.c//'
  274. /********                    Layers.c
  275. *********
  276. *********    Layers - MacLayers Multiwindow BSD Socket Driver
  277. *********
  278. *********          Dave Trissel oakhill!davet
  279. *********
  280. ********* The sockets handling portion of this control module is based 
  281. ********* upon 'screen' by Oliver Laumann whose copyright remains below. 
  282. ********* The rest is
  283.  *
  284.  *             Copyright (C) 1989 by David W. Trissel
  285.  *
  286.  *              Not derived from licensed software.
  287.  *
  288.  * Permission is granted to freely use, copy, modify, and redistribute
  289.  * this software, provided that no attempt is made to gain profit from it,
  290.  * the author is not construed to be liable for any results of using the
  291.  * software, alterations are clearly marked as such, and this notice is
  292.  * not modified.
  293.  *
  294.  */
  295.  
  296. static char LayersVersion[] = "layers 1.10 19-Oct-1991";
  297.  
  298. /* Layers Changes:
  299.  
  300.  
  301.     Version 1.00  17-Mar-1990
  302.  
  303.         First public release.
  304.  
  305.     Version 1.01  10-May-1990
  306.  
  307.         * Fixed bug 001 which caused failure of protocol mode to establish
  308.           if USRLIMIT check is enabled and USRLIMIT or more login shells 
  309.           are already active. Could also keep new login layer windows from
  310.           responding until another layer is brought up front and then sent
  311.           back.
  312.  
  313.     Version 1.01  27-Jun-1991
  314.  
  315.         * Corrected bugs where utmp login record or initial tty settings
  316.           may not be restored if initial client connection fails
  317.  
  318.         * Added return code support so shell scripts can determine what
  319.           happened:
  320.                       0  - layers connected, ran and terminated sucessfully
  321.                       1  - not running under MacLayers client terminal
  322.                       2  - layers terminated due to some abnormal condition
  323.                       3  - SIGQUIT or SIGTERM signal received
  324.                       4  - SIGHUP signal received
  325.  
  326.         * Rewrote protocl.c to avoid using scanf which was prohibiting 7-bit 
  327.           communication lines from working under layers mode. (Scanf does
  328.           not work on 7-bit line in RAW mode since high bit invalidates
  329.           its character checking.)
  330.  
  331.         * Removed internal TERMCAP entries for "ic" and "dc" (insert character
  332.           and delete character) which are not ANSI standard. The "dc" collided
  333.           with a real vt-100 capability that the author did not know about!
  334.           (Note of 6/11/91: perhaps "dc" and "ic" will be reinstated with 
  335.           their true ANSI definitions. 6/11/91)
  336.  
  337.         * If socket directory not 0700 then try to change it to 0700.
  338.  
  339.     Version 1.10  26-Sep-1991
  340.  
  341.         * Host/client version ID sharing at startup. This is transparent on 
  342.           both sides with older versions.
  343.  
  344.             1) If client identifies itself as at least 1.10 MacLayers 
  345.                add vt102 TERMCAP entries for ic, dc, IC, DC with correct
  346.                capabilities. (V1.00 had incorrect ones-see above.)
  347.  
  348. */
  349.  
  350.  
  351. /* Copyright (c) 1987,1988 Oliver Laumann, Technical University of Berlin.
  352.  * Not derived from licensed software.
  353.  *
  354.  * Permission is granted to freely use, copy, modify, and redistribute
  355.  * this software, provided that no attempt is made to gain profit from it,
  356.  * the author is not construed to be liable for any results of using the
  357.  * software, alterations are clearly marked as such, and this notice is
  358.  * not modified.
  359.  *
  360.  *    Modified by Patrick Wolfe (pat@kai.com, kailand!pat)
  361.  *    Do whatever you want with (my modifications of) this program, but
  362.  *    don't claim you wrote them, don't try to make money from them, and
  363.  *    don't remove this notice.
  364.  */
  365.  
  366. /*
  367.  *    Beginning of User Configuration Section
  368.  */
  369.  
  370. /*
  371.  * SEQUENT   -- your host system is Sequent. This changes a setvbuf()
  372.  *              call to a setlinebuf(). Also extends pty search names.
  373.  *
  374.  */
  375. #undef SEQUENT
  376.  
  377.  
  378. /*
  379.  * GETTTYENT -- your system has the new format /etc/ttys (like 4.3 BSD)
  380.  *              and the getttyent(3) library functions.
  381.  *
  382.  */
  383. #undef GETTTYENT
  384.  
  385.  
  386. /*
  387.  * LOGINDEFAULT -- if set to 1 (one), windows will login (add entries to
  388.  *                 /etc/utmp) by default.  Set to 0 if you don't want this.
  389.  *                 (Also see USRLIMIT below). [NOTE: current code always
  390.  *                 logs layer #1 only unless -l option used on 'layers'
  391.  *                 command.]
  392.  */
  393. #define LOGINDEFAULT 0
  394.  
  395. /*
  396.  * USRLIMIT  --   count all non-null entries in /etc/utmp before adding a 
  397.  *                   new entry. Some machine manufacturers (incorrectly) count 
  398.  *                   logins by counting non-null entries in /etc/utmp (instead 
  399.  *                   of counting non-null entries with no hostname and not on 
  400.  *                   a pseudo tty). Sequent does this, so you might reach your 
  401.  *                   limited user license early.
  402.  */
  403. #define USRLIMIT 64
  404.  
  405. /*
  406.  * SOCKDIR      -- If defined, this directory is where layers sockets will be 
  407.  *                   placed, (actually in a subdirectory by the user's loginid).
  408.  *                   This is neccessary because NFS doesn't support socket 
  409.  *                   operations, and many people's homes are on NFS mounted 
  410.  *                   partitions.  Layers will create this directory if it needs 
  411.  *                   to.
  412.  */
  413. #define SOCKDIR "/tmp/layers"    /* NFS doesn't support named sockets */
  414.  
  415. /*
  416.  *    End of User Configuration Section
  417.  */
  418.  
  419. #include <stdio.h>
  420. #include <sgtty.h>
  421. #include <signal.h>
  422. #include <errno.h>
  423. #include <ctype.h>
  424. #include <utmp.h>
  425. #include <pwd.h>
  426. #include <nlist.h>
  427. #include <fcntl.h>
  428. #include <sys/types.h>
  429. #include <sys/time.h>
  430. #include <sys/file.h>
  431. #include <sys/wait.h>
  432. #include <sys/socket.h>
  433. #include <sys/un.h>
  434. #include <sys/stat.h>
  435. #include <sys/dir.h>
  436. #include <sys/ioctl.h>
  437.  
  438. #include "layers.h"
  439.  
  440. #ifdef GETTTYENT
  441. #include <ttyent.h>
  442. #else
  443. static struct ttyent
  444.   { char *ty_name;
  445.   } *getttyent();
  446. static char *tt, *ttnext;
  447. static char ttys[] = "/etc/ttys";
  448. #endif
  449.  
  450. #ifndef FSCALE
  451. #define FSCALE 1000.0        /* Sequent doesn't define FSCALE...grrrr */
  452. #endif
  453.  
  454. #ifdef  USRLIMIT
  455. struct utmp utmpbuf;
  456. int UserCount;
  457. #endif
  458.  
  459. #define Ctrl(c) ((c)&037)
  460.  
  461. /* C library items */
  462. extern char **environ;
  463. extern errno;
  464. extern sys_nerr;
  465. extern char *sys_errlist[];
  466. extern char *index(), *rindex(), *malloc(), *getenv();
  467. extern char *getlogin(), *ttyname();
  468.  
  469. /* Local items */
  470. static void FAbort(), SigHup(), SigChld(), AddCap(), FinitTerm();
  471. static char  *MakeTermcap(), *Filename(), **SaveArgs(), *GetTtyName();
  472. static void    InitWorld(), ClearShape(), BuildTitle(), KillPG();
  473. static void SetWindowSize(), WriteUtmp();
  474. static int    ReadUtmp(), FindUtmp(), SetUtmp();
  475.  
  476. static int    loginflag = -1;
  477. static char PtyName[32], TtyName[32];
  478. static char *ShellProg;
  479. static char *ShellArgs[2];
  480. static inlen;
  481. static ESCseen;
  482. static GotSignal;
  483. static char DefaultShell[] = "/bin/sh";
  484. static char DefaultPath[] = ":/usr/ucb:/bin:/usr/bin";
  485. static char PtyProto[] = "/dev/ptyXY";
  486. static char TtyProto[] = "/dev/ttyXY";
  487. static int TtyMode = 0622;
  488. static struct stat RealTtyStat;                    /* Real tty stat */
  489. static char RealTtyName[32] = "";                /* Real tty name */
  490. static int    RealSlot = 0;                        /* Real tty logon slot */
  491. static struct utmp    RealUtmp;                    /* Real tty logon utmp entry */
  492. static int    RealTtyMode = 0;                    /* Real tty mode */
  493. static int    Oumask;                                /* Original user's umask */
  494. static char SockPath[512];
  495. #ifdef SOCKDIR
  496. static char SockDir[] = SOCKDIR;
  497. #else
  498. static char SockDir[] = ".layers";
  499. #endif
  500. static char *SockNamePtr, *SockName;
  501. static ServerSocket;
  502. static char *NewEnv[MAXARGS];
  503. static char Esc = Ctrl('a');
  504. static char MetaEsc = 'a';
  505. static char *home;
  506. static Abortonmsg = 0;
  507. static Resetenvonmsg = 0;
  508. static utmp, utmpf;
  509. static char UtmpName[] = "/etc/utmp";
  510. static char *LoginName;
  511. static mflag, nflag, fflag, rflag;
  512. static char HostName[MAXSTR];
  513. static char *myname;
  514. static DevTty;
  515.  
  516. static struct mode {
  517.     struct sgttyb m_ttyb;
  518.     struct tchars m_tchars;
  519.     struct ltchars m_ltchars;
  520.     int m_ldisc;
  521.     int m_lmode;
  522. } OldMode, NewMode;
  523.  
  524. #define MSG_CREATE    0
  525. #define MSG_ERROR     1
  526.  
  527. struct msg
  528.   {
  529.     int type;
  530.     union
  531.       { struct
  532.           {    int    lflag;                /* login flag */
  533.             struct Shape shape;        /* window shape */
  534.             int nargs;
  535.             char line[MAXLINE];
  536.             char dir[1024];
  537.           } create;
  538.         char message[MAXLINE];
  539.       } m;
  540.   };
  541.  
  542.  
  543.             /* dynamic keyboard input buffer definition */
  544. struct Kbuff
  545.   {    struct Kbuff * next;            /* next buffer in chain (or NULL) */
  546.     int            size;                /* size of data in this buffer */
  547.     int            offset;                /* start of first data in buffer */
  548.     unsigned char text[IOSIZE];        /* text buffer itself */
  549.   };
  550.  
  551.             /* World layer definition */
  552. struct Layer {
  553.     int        chan;                    /* channel represented by this layer */
  554.     int        allocated;                /* layer allocated */
  555.     int        ptyfd;                    /* psuedo tty */
  556.     int        ptymask;                /* mask for pty descriptor */
  557.     int        lpid;                    /* layer head process ID */
  558.     int        slot;                    /* utmp slot number */
  559.     struct Kbuff *kbuff;            /* keyboard input buffers */
  560.     struct Shape shape;                /* Shape structure to/from MacLayers */
  561.     char    cmd[MAXSTR];            /* command to execute */
  562.     char    tty[MAXSTR];            /* psuedo tty ID */
  563.     };
  564.  
  565. static struct Layer World[MAXPCHAN]; /* all layer structures */
  566.  
  567. static int rows = 24;                /* default window height in lines */
  568. static int cols = 80;                /* default window width in chars */
  569. static char Termcap[1024];
  570. static char Term[MAXSTR] = "TERM=";    /* window's terminal type */
  571. static char    *UserTerm;                /* terminal ID we are mimmicing */
  572. static int flowctl;
  573. static tcLineLen = 100;
  574.  
  575. #define EXITNORMAL        0            /* normal exit - connection succeeded */
  576. #define EXITNOMACLAYERS    1            /* not running to MacLayers terminal */
  577. #define EXITABNORMAL    2            /* something wrong generic error */
  578. #define EXITSIGQUIT        3            /* TERM or QUIT signal got us */
  579. #define EXITSIGHUP        4            /* HUP signal got us */
  580.  
  581. static exitcode = EXITABNORMAL;        /* default to abnormal exit */
  582.  
  583. /* co#80 and li$24 added dynamically for proper window size */
  584. static char TermcapConst1[] = "TERMCAP=SC|";
  585. static char TermcapConst3[] = "|MacLayers virtual terminal|\\\n\
  586.     :cr=^M:do=^J:nl=^J:bl=^G:cl=\\E[;H\\E[2J:\\\n\
  587.     :le=^H:bs:am:cm=\\E[%i%d;%dH:nd=\\E[C:up=\\E[A:\\\n\
  588.     :ce=\\E[K:cd=\\E[J:so=\\E[7m:se=\\E[m:us=\\E[4m:ue=\\E[m:\\\n\
  589.     :md=\\E[1m:mr=\\E[7m:mb=\\E[5m:me=\\E[m:is=\\E[1;24r\\E[24;1H:\\\n\
  590.     :rf=/usr/lib/tabset/vt100:\\\n\
  591.     :rs=\\E>\\E[?3l\\E[?4l\\E[?5l\\E[?7h\\E[?8h:ks=\\E[?1h\\E=:ke=\\E[?1l\\E>:\\\n\
  592.     :ku=\\EOA:kd=\\EOB:kr=\\EOC:kl=\\EOD:kb=^H:\\\n\
  593.     :ho=\\E[H:k1=\\EOP:k2=\\EOQ:k3=\\EOR:k4=\\EOS:ta=^I:pt:sr=\\EM:vt#3:xn:\\\n\
  594.     :sc=\\E7:rc=\\E8:cs=\\E[%i%d;%dr:\\\n\
  595.     :";
  596.     /* remove illegal "dc" which is ANSI/vt-100 reverse index  V1.81 */
  597. #if 0
  598.     :dc=\\ED:ic=\\EI:";
  599. /* NOTE: the above two cababilities are beyond vt100 - unique to MacLayers */
  600. #endif
  601.  
  602.  /* The following supported by MacLayers versions 1.1 and later */
  603.  /* ANSI insert characters and delete characters */
  604. static char TermcapConst101[] = "ic=\\E[@:dc=\\E[P:IC=\\E[%d@:DC=\\E[%dP:";
  605.  
  606. int        Dflag;                            /* debug dump flag */
  607. int        Clientlevel = 1;                /* client protocol (Default to V1.00) */
  608. int        Protocollevel = 1;                /* effective protocol (default 1) */
  609.  
  610.                             /* main() */
  611. int
  612. main(ac, av)
  613. char **av;
  614. {
  615.     register n;
  616.     register len;
  617.     register struct Layer *layer;
  618.     char    *ap;
  619.     struct passwd *ppp;
  620.     int        s;
  621.     int        r;                            /* read fd test bits */
  622.     int        w;                            /* write fd test bits */
  623.     int        stall;                        /* stall flag for priority channel */
  624.     int        fderr;                        /* error fd test bits */
  625.     struct timeval tv;
  626.     struct Shape shape;                    /* window shape */
  627.     time_t    now;
  628.     char    buf[IOSIZE];
  629.     char    rc[256];
  630.     struct stat st;
  631.     struct Kbuff *kbptr;                /* input keyboard buffer pointer */
  632.  
  633.     Abortonmsg = 1;                        /* quit if message generated */
  634.     ClearShape(&shape);                    /* initialize shape structure */
  635.     myname = (ac == 0) ? "layers" : av[0];
  636.     InitWorld();                        /* clear World array structures */
  637.  
  638.     while (ac > 0)
  639.       {    ap = *++av;
  640.         if (--ac > 0 && *ap == '-')
  641.           {    switch (ap[1])
  642.             { case 'l':        /* login this command line */
  643.                 loginflag = 1;
  644.                 break;
  645.  
  646.               case 'd':        /* dump debugging flag */
  647.                 Dflag = 1;
  648.                 (void) freopen("layers.dump", "a", stderr); /* append mode */
  649. #ifdef SEQUENT
  650.                 setlinebuf(stderr);
  651. #else
  652.                 setvbuf(stderr, NULL, _IOLBF, 0);
  653. #endif
  654.                 break;
  655.  
  656.               case 'u':        /* do not login this command line */
  657.                 loginflag = 0;
  658.                 break;
  659.  
  660.               case 'm':        /* force this to be master and not a client */
  661.                 mflag = 1;
  662.                 break;
  663.  
  664.               case 'n':        /* no flow control */
  665.                 nflag = 1;
  666.                 break;
  667.  
  668.               case 'f':        /* flow control on */
  669.                 fflag = 1;
  670.                 break;
  671.  
  672.               case 'v':        /* do nothing but issue layers version */
  673.                 printf("%s\n", LayersVersion);
  674.                 exit(EXITNORMAL);
  675.  
  676.               default:
  677.             help:
  678.                 Msg (0,"Use: %s [-f] [-l | -u] [-m] [-n] [cmd args]\n", myname);
  679.  
  680.             } /* end switch on '-' option */
  681.  
  682.         } /* end if '-' */
  683.  
  684.         else
  685.             break;
  686.  
  687.       } /* end while parameters */
  688.  
  689.     if (nflag && fflag)
  690.         Msg (0, "-f and -n are conflicting options.");
  691.  
  692.     if ((ShellProg = getenv ("SHELL")) == 0)
  693.         ShellProg = DefaultShell;
  694.     DO DEBUG("ShellProg %s\n", ShellProg);
  695.  
  696.     /* we mimmic the user's $TERM ID */
  697.     if ((UserTerm = getenv("TERM")) == 0)
  698.         UserTerm = "layers";                /* use "layers" if none */
  699.     (void) strcat(Term, UserTerm);
  700.     DO DEBUG("%s\n", Term);
  701.  
  702.     ShellArgs[0] = ShellProg;
  703.     if (ac == 0)
  704.       { ac = 1;
  705.         av = ShellArgs;
  706.         shape.wattr |= Wa_shell;            /* indicate a shell window */
  707.       }
  708.  
  709.     if ((home = getenv ("HOME")) == 0)
  710.         Msg (0, "$HOME is undefined.");
  711.     DO DEBUG("home %s\n", home);
  712.  
  713.     if ((LoginName = getlogin ()) == 0 || LoginName[0] == '\0')
  714.       { if ((ppp = getpwuid (getuid ())) == 0)
  715.                return;
  716.         LoginName = ppp->pw_name;
  717.       }
  718.     DO DEBUG("LoginName %s\n", LoginName);
  719.  
  720.     if ((Oumask=umask(0)) == -1)
  721.         Msg (errno, "Cannot change umask to zero");
  722.     DO DEBUG("Original umask o%o\n", Oumask);
  723.  
  724. #ifdef SOCKDIR
  725.     if (stat (SOCKDIR, &st) == -1)
  726.       {    if (errno == ENOENT)
  727.           { if (mkdir (SOCKDIR, 0777) == -1)
  728.                 Msg (errno, "Cannot make directory %s", SOCKDIR);
  729.             (void) chown (SOCKDIR, 0, 0);
  730.           }
  731.         else
  732.             Msg (errno, "Cannot get status of %s", SOCKDIR);
  733.       }
  734.     else
  735.       { if ((st.st_mode & S_IFMT) != S_IFDIR)
  736.             Msg (0, "%s is not a directory.", SOCKDIR);
  737.         if ((st.st_mode & 0777) != 0777)
  738.             Msg (0, "Directory %s must have mode 777.", SOCKDIR);
  739.       }
  740.     sprintf (SockPath, "%s/%s", SockDir, LoginName);
  741. #else
  742.     sprintf (SockPath, "%s/%s", home, SockDir);
  743. #endif
  744.     DO DEBUG("SockPath %s\n", SockPath);
  745.  
  746.     if (stat (SockPath, &st) == -1)
  747.       { if (errno == ENOENT)
  748.           { if (mkdir (SockPath, 0700) == -1)
  749.                 Msg (errno, "Cannot make directory %s", SockPath);
  750.             (void) chown (SockPath, getuid (), getgid ());
  751.             DO DEBUG("SockPath directory made\n");
  752.           }
  753.         else
  754.             Msg (errno, "Cannot get status of %s", SockPath);
  755.       }
  756.     else
  757.       { if ((st.st_mode & S_IFMT) != S_IFDIR)
  758.                Msg (0, "%s is not a directory.", SockPath);
  759.         if ((st.st_mode & 0777) != 0700)
  760.           { if (chmod(SockPath, 0700) == -1)
  761.                 Msg(0, "Cannot change directory %s to mode 700.", SockPath);
  762.           }
  763.         if (st.st_uid != getuid ())
  764.             Msg (0, "You are not the owner of %s.", SockPath);
  765.       }
  766.  
  767.     (void) strcpy(RealTtyName, GetTtyName());        /* real tty name */
  768.     if (stat(RealTtyName, &RealTtyStat) == -1)        /* get current mode */
  769.         Msg(errno, "Cannot get status of %s", RealTtyName);
  770.     DO DEBUG("Mode of %s is %#o\n", RealTtyName, RealTtyStat.st_mode);
  771.     RealTtyMode = RealTtyStat.st_mode;        /* save mode for later restore */
  772.  
  773.     (void) gethostname (HostName, MAXSTR);
  774.     HostName[MAXSTR-1] = '\0';
  775.     DO DEBUG("HostName %s\n", HostName);
  776.  
  777.     if (ap = index (HostName, '.'))
  778.         *ap = '\0';
  779.     if (ap)
  780.         DO DEBUG("*ap %s\n", *ap);
  781.  
  782.     strcat (SockPath, "/");
  783.     SockNamePtr = SockPath + strlen (SockPath);
  784.  
  785.     /* if we are a client send create message to startup window and exit */
  786.     if (GetSockName ())
  787.       {    DO DEBUG("GetSockName says that we are client\n");
  788.         DO DEBUG("SockName '%s'\n", SockName);
  789.         s = MakeClientSocket (1);
  790.         DO DEBUG("Client socket is %d\n", s);
  791.         DO DEBUG("SendCreateMsg()\n");
  792.         SendCreateMsg (s, ac, av, loginflag, &shape);
  793.         close (s);
  794.         DO DEBUG("after SendCreateMsg(), now exit(EXITNORMAL)\n");
  795.         exit (EXITNORMAL);
  796.       }
  797.  
  798.     /* we are the server */
  799.     DO DEBUG("SockName '%s'\n", SockName);
  800.     DO DEBUG("We are server\n");
  801.     if ((DevTty = open ("/dev/tty", O_RDWR|O_NDELAY)) == -1)
  802.         Msg (errno, "/dev/tty");
  803.     DO DEBUG("opened /dev/tty fd %d\n", DevTty);
  804.  
  805.     ServerSocket = MakeServerSocket ();
  806.     DO DEBUG("ServerSocket %d\n", ServerSocket);
  807.     s = ServerSocket;
  808.  
  809.     if (fflag)
  810.         flowctl = 1;
  811.     else
  812.     if (nflag)
  813.         flowctl = 0;
  814.  
  815.     if (loginflag == -1)
  816.         loginflag = LOGINDEFAULT;
  817.  
  818.     MakeNewEnv ();
  819.  
  820.     Resetenvonmsg = 1;                    /* cleanup Utmp and tty if abort */
  821.  
  822.     GetTTY (0, &OldMode);
  823.     SetMode (&OldMode, &NewMode);
  824.     SetTTY (0, &NewMode);
  825.  
  826.     InitUtmp ();
  827.     RealSlot = FindUtmp(RealTtyName);    /* find current logon slot */
  828.     if (RealSlot)
  829.       {    if (ReadUtmp(RealSlot, &RealUtmp) > 0)    /* read real login utmp */
  830.             RemoveUtmp(RealSlot);        /* remove original logon slot */
  831.         else
  832.             RealSlot = 0;                /* something's wrong */
  833.       }
  834.  
  835.     signal (SIGHUP, SigHup);
  836.     signal (SIGINT, SIG_IGN);            /* we should never see this */
  837.     signal (SIGQUIT, FAbort);            /* quit layers on these 2 signals */
  838.     signal (SIGTERM, FAbort);
  839.     signal (SIGTTIN, SIG_IGN);
  840.     signal (SIGTTOU, SIG_IGN);
  841.     signal (SIGALRM, SIG_IGN);            /* alarm clock used by protocol.c */
  842.  
  843.     if (Initlink() == 0)
  844.       {    exitcode = EXITNOMACLAYERS;        /* return special status code */
  845.         Msg (0, "\n\n  You are not running under MacLayers.");
  846.       }
  847.         
  848.     sprintf (rc, "%.*s/.layersrc", 245, home);
  849. #if 0 /* NOT YET SUPPORTED */
  850.     /* if no window list start up a default shell window */
  851.     if (ReadRc(rc) == 0)            
  852. #endif
  853.       {    n = MakeWindow (0, *av, av, (char *)0, loginflag, &shape);
  854.         if (n == -1)
  855.             { SetTTY (0, &OldMode);
  856.             FQuit(EXITABNORMAL);
  857.             /* NOT REACHED */
  858.             }
  859.       }
  860.  
  861.     (void) chmod(RealTtyName, 0600);        /* lock out broadcasts */
  862.     Abortonmsg = 0;                            /* don't abort on msg from now on */
  863.     Resetenvonmsg = 0;                        /* no cleanup - messages normal */
  864.     signal (SIGCHLD, SigChld);
  865.     tv.tv_usec = 0;
  866.     tv.tv_sec = 0;                            /* default no timer wanted */
  867.  
  868.     /* client/Maclayers processing loop */
  869.  
  870.     /* poll .20 secs for new startups */
  871. #define WUSSTARTUP    200000                
  872.     /* stall nonpriority windows .5 seconds when top window I/O active */
  873. #define WUSSTALL    500000
  874.  
  875.     stall = 0;                                /* startout no stalled channels */
  876.     fderr = 0;                                /* startout no error fd's */
  877.  
  878.     while (1)
  879.       {    int            priochan;                /* the top window channel */
  880.  
  881.         priochan = TopChannel();            /* find highest priority channel */
  882.  
  883.         /* check for I/O on all available I/O descriptors */
  884.         r = 1<<0;                            /* always read MacLayers stream */
  885.         r |= 1<<s;                            /* always read server socket */
  886.         w = 0;                                /* initalize to no write tests */
  887.         tv.tv_usec = 0;                        /* default no startup poll */
  888.  
  889.         /* for all active layers set read and write bits as appropriate */
  890.         if (stall)
  891.             stall = 1;                        /* start counting output layers */
  892.         for (n=0; n<MAXPCHAN; n++)
  893.          if ((layer = &World[n])->allocated) /* if layer exists ... */
  894.           {    /* if not yet started or has just terminated ... */
  895.             if (layer->ptymask & fderr)
  896.                 tv.tv_usec = WUSSTARTUP;    /* don't spinloop but wait-a-bit */
  897.             else
  898.                 {    if (layer->kbuff && layer->kbuff->size)
  899.                     /* keyboard input for layer */
  900.                     w |= layer->ptymask;    /* try write to it */
  901.                 /* read layer output unless we're being nice to top window */
  902.                 if (!stall)
  903.                     r |= layer->ptymask;    /* read output from layer */
  904.                 else
  905.                 if (layer->chan == priochan)
  906.                     r |= layer->ptymask;    /* read top priority output */
  907.                 else
  908.                     stall++;                /* indicate something to stall */
  909.                }
  910.             }
  911.  
  912.         if (stall > 1)
  913.             if (!tv.tv_usec)
  914.                 tv.tv_usec = WUSSTALL;        /* set stall timout */
  915.  
  916.         /* process signals before trying select */
  917.         if (GotSignal)
  918.           { SigHandler ();
  919.             continue;
  920.           }
  921.  
  922.         DO DEBUG("Select(r %x, w %x, fderr %x, stall %d, prio %d, us %d)\n",
  923.                     r, w, fderr, stall, priochan, tv.tv_usec);
  924.  
  925.         switch ( select(32, &r, &w, NULL, tv.tv_usec ? &tv : NULL) )
  926.         { case -1:
  927.             /* errno has report */
  928.             if (errno == EINTR)                /* signal delivered or timout */
  929.               { errno = 0;
  930.                 tv.tv_usec = 0;                /* clear timer wait value */
  931.                 fderr = 0;                    /* turn off error stall */
  932.                 stall = 0;                    /* turn off output priority stall */
  933.                 DO DEBUG("select errno EINTR\n");
  934.                 continue;                    /* re-loop */
  935.               }
  936.             Abortonmsg = 1;
  937.             Resetenvonmsg = 1;                /* clean up tty settings */
  938.             DO DEBUG("select errno %d\n", errno);
  939.             Msg (errno, "select");
  940.             /*NOTREACHED*/
  941.  
  942.           case 0:
  943.             /* timeout reached */
  944.             tv.tv_usec = 0;                    /* clear timer wait value */
  945.             stall = 0;                        /* turn off stall */
  946.             fderr = 0;                        /* turn off error stall */
  947.             continue;                        /* re-loop */
  948.  
  949.           default:
  950.             /* a channel has read/write status pending */
  951.             break;
  952.         }
  953.  
  954.         DO DEBUG("after select r %x w %x\n", r, w);
  955.  
  956.         /* handle any signal arriving up during select wait */
  957.         if (GotSignal)
  958.           { SigHandler ();
  959.             continue;
  960.           }
  961.  
  962.         /* if server socket has command process that now */
  963.         if (r & 1 << s)
  964.           {    ReceiveMsg(s);                    /* process client control packet */
  965.             continue;                        /* status may have changed */
  966.           }
  967.  
  968.         /* next process input stream from MacLayers */
  969.         if (r & 1 << 0)
  970.           { ProcessStreamin();                /* key input and control packets */
  971.             continue;                        /* status may have changed */
  972.           }
  973.  
  974.         /* process keyboard input first so output doesn't hold up
  975.         ** keyboard echo and break/interrupt processing
  976.         */
  977.         priochan = TopChannel();            /* find top priority channel */
  978.         stall = 0;                            /* assume no stall needed */
  979.         for (n=0; n<MAXPCHAN; n++)
  980.           if ((layer = &World[n])->allocated)
  981.             if (w & layer->ptymask)
  982.                 while ((kbptr=layer->kbuff)->size)
  983.                   {    /* pass as much keyboard as possible */
  984.                     if (layer->chan == priochan)
  985.                         stall = 1;            /* stall lower priority channels */
  986.                     len = write(layer->ptyfd, &kbptr->text[kbptr->offset],
  987.                                  kbptr->size);
  988.                     DO DEBUG("keyin len %d to chan %d\n", len, layer->chan);
  989.                     if (len <= 0)            /* if no data accepted ... */
  990.                       {    if (errno == EIO)    /* if I/O error indicated ... */
  991.                             fderr |= layer->ptymask; /* wait-a-bit on this */
  992.                         errno = 0;            /* clear errno */
  993.                         break;                /* try again later */
  994.                       }
  995.                     /* some of buffer accepted */
  996.                     kbptr->size -= len;        /* length processed */
  997.                     kbptr->offset += len;    /* bump up offset */
  998.                     if (kbptr->size > 0)    /* not all buffer accepted ... */
  999.                         break;                /* try feed again later */
  1000.                     /* see if another buffer chained */
  1001.                     if (kbptr->next)
  1002.                       {    /* yes, free up current buffer and queue next */
  1003.                         layer->kbuff = kbptr->next; /* to next buffer */
  1004.                         free(kbptr);    /* free this buffer up */
  1005.                       }
  1006.                     else
  1007.                       {    /* otherwise leave this for next input */
  1008.                         kbptr->size = 0;    /* empty buffer */
  1009.                         kbptr->offset = 0;    /* refill from the start */
  1010.                       }
  1011.                   }
  1012.  
  1013.         /* first process the highest priority channel (top window) */
  1014.         if (priochan > 0 && priochan <= MAXPCHAN) /* if valid ... */
  1015.           if ((layer = &World[priochan-1])->allocated)
  1016.             if (r & layer->ptymask)
  1017.               {    /* output to send to top MacLayers window */
  1018.                 len = read(layer->ptyfd, buf, IOSIZE);
  1019.                 if (len >= 0)                /* if no error ... */
  1020.                   {    DO DEBUG("read output len %d chan %d\n", len, layer->chan);
  1021.                   }
  1022.                 else
  1023.                   {    /* We expect EIO error if socket not yet open on other end
  1024.                     ** or if process using socket has terminated. We expect
  1025.                     ** EWOULDBLOCK also after process terminates.
  1026.                     **/
  1027.                     DO DEBUG("read output err chan %d errno %d len %d\n",
  1028.                                 layer->chan, errno, len);
  1029.                     if (errno == EIO || errno == EWOULDBLOCK)
  1030.                         DO DEBUG(" ...anticipated\n");
  1031.                     /* layer not ready or just terminated so wait-a-bit */
  1032.                     fderr |= layer->ptymask;
  1033.                     r &= ~layer->ptymask; /* don't read it again below */
  1034.                     errno = 0;                /* clear errno */
  1035.                   }
  1036.                 if (len > 0)
  1037.                     SendData(layer->chan, buf, len);
  1038.  
  1039.                 if (len >= 0)
  1040.                     /* To keep lower priority channels from hogging the line
  1041.                     ** we delay any output from them until the primary window 
  1042.                     ** has no more data to be sent to it.
  1043.                     */
  1044.                     stall = 1;                /* stall output from others */
  1045.               }
  1046.  
  1047.         /* now pass all available output to MacLayers */
  1048.         if (!stall)
  1049.          for (n=0; n<MAXPCHAN; n++)
  1050.           if ((layer = &World[n])->allocated)
  1051.             if (r & layer->ptymask)
  1052.               {    /* output to send to MacLayers window */
  1053.                 len = read(layer->ptyfd, buf, IOSIZE);
  1054.                 if (len >= 0)                /* if no error ... */
  1055.                   {    DO DEBUG("output chan %d len %d\n", layer->chan, len);
  1056.                   }
  1057.                 else
  1058.                   {    /* We expect EIO error if socket not yet open on other end
  1059.                     ** or if process using socket has terminated. We expect
  1060.                     ** EWOULDBLOCK also after process terminates.
  1061.                     **/
  1062.                     DO DEBUG("read output err chan %d errno %d len %d\n",
  1063.                                 layer->chan, errno, len);
  1064.                     if (errno == EIO || errno == EWOULDBLOCK)
  1065.                       {    DO DEBUG(" ...anticipated\n");
  1066.                       }
  1067.                     /* layer not ready or just terminated so wait-a-bit */
  1068.                     fderr |= layer->ptymask;
  1069.                     errno = 0;                /* clear errno */
  1070.                   }
  1071.                 if (len > 0)
  1072.                     SendData(layer->chan, buf, len);
  1073.               }
  1074.  
  1075.         /* handle signals again */
  1076.         if (GotSignal)
  1077.             SigHandler ();
  1078.  
  1079.       } /* end while (1) */
  1080.  
  1081.     /* NOT REACHED */
  1082.  
  1083. } /* main() */
  1084.  
  1085.                     /* ReceiveQuit() - MacLayers sends Quit packet */
  1086.  
  1087. void
  1088. ReceiveQuit()
  1089. {
  1090.     /* We completely quit layers cancelling all active processes */
  1091.     DO DEBUG("ReceiveQuit()\n");
  1092.     FQuit(EXITNORMAL);                    /* normal termination */
  1093.     /* NOT REACHED */
  1094.  
  1095. } /* ReceiveQuit() */
  1096.  
  1097.  
  1098.                 /* ReceiveNew() - MacLayers requests a new shell layer */
  1099.  
  1100. void
  1101. ReceiveNew(chanid, shape)
  1102. int        chanid;                                /* channel for new shell layer */
  1103. struct Shape *shape;                        /* shape for new channel */
  1104. {
  1105.     DO DEBUG("ReceiveNew(%d)\n", chanid);
  1106.     (void) MakeWindow (chanid, *ShellArgs, ShellArgs,
  1107.                     (char *) 0, loginflag, shape);
  1108.  
  1109. } /* ReceiveNew() */
  1110.  
  1111.  
  1112.                 /* ReceiveDelete() - MacLayers has removed a layer */
  1113. void
  1114. ReceiveDelete(chanid)
  1115. int        chanid;                                /* channel which was deleted */
  1116. {
  1117.     struct Layer *layer;                    /* layer pointer */
  1118.  
  1119.     /* validate channel */
  1120.     DO DEBUG("ReceiveDelete(%d)\n", chanid);
  1121.     if (chanid <= 0 || chanid > MAXPCHAN)
  1122.         return;                                /* ignore invalid channel */
  1123.  
  1124.     /* if this layer active then kill it off, else ignore request */
  1125.     layer = &World[chanid-1];                /* locate target layer */
  1126.     if (layer->allocated)
  1127.         KillWindow(layer);
  1128.  
  1129. } /* ReceiveDelete() */
  1130.     
  1131.     
  1132.         /* ReceiveSignal() - send signal to layer's process group */
  1133.  
  1134. void
  1135. ReceiveSignal(chanid, signal)
  1136. int            chanid;                            /* layer's channel */
  1137. int            signal;                            /* signal.h signal ID */
  1138. {
  1139.     struct Layer *layer;                    /* layer pointer */
  1140.  
  1141.     DO DEBUG("ReceiveSignal(%d,%d)\n", chanid, signal);
  1142.     /* verify channel */
  1143.     if (chanid <= 0 || chanid > MAXPCHAN)
  1144.         return;                                /* ignore invalid channel */
  1145.  
  1146.     /* if this layer is active send the signal to the process group */
  1147.     layer = &World[chanid-1];                /* locate target layer */
  1148.     if (layer->allocated && layer->lpid)
  1149.         KillPG(layer, signal);
  1150.  
  1151. } /* ReceiveSignal() */
  1152.  
  1153.  
  1154.                 /* ReceiveReshape() - windowsize and location updated */
  1155. void
  1156. ReceiveReshape(chanid, shape)
  1157. int                chanid;                    /* channel having shape */
  1158. struct Shape    *shape;                    /* shape structure */
  1159. {
  1160.     struct Layer *layer;                /* layer pointer */
  1161.  
  1162.     DO DEBUG("ReceiveReshape(%d)\n", chanid);
  1163.  
  1164.     /* verify channel */
  1165.     if (chanid <= 0 || chanid > MAXPCHAN)
  1166.         return;                                /* ignore invalid channel */
  1167.  
  1168.     /* if this layer is active then reshape it's window */
  1169.     layer = &World[chanid-1];                /* locate target layer */
  1170.     if (layer->allocated && layer->lpid)
  1171.       {    layer->shape = *shape;                /* install as our new shape */
  1172.         SetWindowSize(layer);                /* udpate the O/S window info */
  1173.       }
  1174.  
  1175. } /* ReceiveReshape() */
  1176.  
  1177.  
  1178.             /* SetWindowSize() - tell O/S about new window size */
  1179.  
  1180. static void
  1181. SetWindowSize(layer)
  1182. struct Layer    *layer;                    /* layer to resize */
  1183. {
  1184. #ifdef TIOCSWINSZ
  1185.     struct    winsize    wsize;                /* window size structure */
  1186.     int            retcode;                /* ioctl return code */
  1187.  
  1188.     wsize.ws_col = layer->shape.wchars; /* character width */
  1189.     wsize.ws_row = layer->shape.wlines; /* window height */
  1190.     wsize.ws_xpixel = 0;                /* necessary? */
  1191.     wsize.ws_ypixel = 0;
  1192.     /* update O/S window state */
  1193.     retcode = ioctl(layer->ptyfd, TIOCSWINSZ, &wsize);
  1194.     DO DEBUG("SetWindowSize(chan %d) col %d, row %d iotcl() = %d\n",
  1195.             layer->chan, layer->shape.wchars, layer->shape.wlines,
  1196.             retcode);
  1197.  
  1198.     retcode = ioctl(layer->ptyfd, TIOCGWINSZ, &wsize);
  1199.     DO DEBUG("TIOCGWINSZ: col %d, row %d iotcl() = %d\n",
  1200.             wsize.ws_col, wsize.ws_row, retcode);
  1201.  
  1202. #endif
  1203. }  /* SetWindowSize() */
  1204.  
  1205.  
  1206.                 /* ReceiveData() - received keyboard input for layer */
  1207. void
  1208. ReceiveData(chanid, buff, cnt)
  1209. int        chanid;                            /* channel receiving input */
  1210. char    *buff;                            /* buffer containing data */
  1211. int        cnt;                            /* count of data bytes */
  1212. {
  1213.     struct Layer *layer;                /* layer pointer */
  1214.     struct Kbuff *kb;                    /* keybuff pointer */
  1215.  
  1216.     DO DEBUG("ReceiveData(%d, '%.*s')\n", chanid, cnt, buff);
  1217.     /* verify channel */
  1218.     if (chanid <= 0 || chanid > MAXPCHAN)
  1219.         return;                                /* ignore invalid channel */
  1220.     layer = &World[chanid-1];                /* locate target layer */
  1221.  
  1222.     /* add character stream to layer's input buffers for main loop processing */
  1223.     for (kb=layer->kbuff; kb->next; kb=kb->next); /* find oldest buffer */
  1224.     while (cnt--)
  1225.       {    
  1226.         /* if current buffer full then chain in a new one */
  1227.         if (kb->offset+kb->size >= IOSIZE)
  1228.           { kb->next = (struct Kbuff *) malloc(sizeof(struct Kbuff));
  1229.             kb = kb->next;                    /* base new keybuff */
  1230.             kb->next = NULL;                /* no next yet */
  1231.             kb->size = 0;                    /* this character is first */
  1232.             kb->offset = 0;                    /* at zero offset */
  1233.           }
  1234.  
  1235.         /* add new character to the end of this buffer */
  1236.         kb->text[kb->offset+kb->size++] = *buff++; /* insert at end of data */
  1237.       }
  1238.  
  1239. } /* ReceiveData() */
  1240.  
  1241.  
  1242.  
  1243.                     /* InitWorld() - initialize layer structures */
  1244.  
  1245. static void
  1246. InitWorld()
  1247. {
  1248.     struct Layer *layer;                /* layer pointer */
  1249.     struct Kbuff *kb;                    /* keybuff pointer */
  1250.     int        i;                            /* work variable */
  1251.  
  1252.     for (i=0; i<MAXPCHAN; i++)
  1253.       {    layer = &World[i];                /* point to layer */
  1254.         layer->chan = i+1;                /* channel ID */
  1255.         layer->allocated = 0;            /* does not exist yet */
  1256.         layer->lpid = 0;                /* head process */
  1257.         layer->ptyfd = 0;                /* no pseduo pty yet */
  1258.         layer->ptymask = 0;                /* no pty mask yet */
  1259.         layer->slot = 0;                /* no Utmp slot */
  1260.         ClearShape(&layer->shape);        /* clear shape structure */
  1261.  
  1262.         /* allocate the primary input keybuffer for this layer */
  1263.         layer->kbuff = (struct Kbuff *) malloc(sizeof(struct Kbuff));
  1264.         layer->kbuff->next = NULL;        /* no next buffer */
  1265.         layer->kbuff->size = 0;            /* no data in buffer */
  1266.         layer->kbuff->offset = 0;        /* start filling at front */
  1267.  
  1268.       } /* end for layer scan */
  1269.  
  1270. } /* InitWorld() */
  1271.  
  1272.  
  1273.                     /* clearshape() - initialize shape structure */
  1274.  
  1275. static void
  1276. ClearShape(shape)
  1277. struct Shape    *shape;                    /* shape structure pointer */
  1278. {
  1279.     shape->worigv = 0;                    /* default window position */
  1280.     shape->worigh = 0;
  1281.     shape->wlines = 0;                    /* default size */
  1282.     shape->wchars = 0;
  1283.     shape->wfont = 0;                    /* default font size */
  1284.     shape->wattr = 0;                    /* no attributes */
  1285.  
  1286. } /* clearshape() */
  1287.  
  1288.  
  1289.                     /* SigHandler() - process signals */
  1290.  
  1291. SigHandler ()
  1292. {
  1293.     DO DEBUG("GotSignal()\n");
  1294.     while (GotSignal)
  1295.       { GotSignal = 0;
  1296.         DoWait ();        /* handle dead or stopped children processes */
  1297.       }
  1298. }
  1299.  
  1300. static void
  1301. SigChld ()
  1302. {
  1303.     DO DEBUG("SigChld()\n");
  1304.     /* flag child process is stopped or dead */
  1305.     GotSignal = 1;
  1306. }
  1307.  
  1308. static void
  1309. SigHup ()
  1310. {
  1311.     DO DEBUG("SigHup()\n");
  1312.     /* Detach (0); */
  1313.     FQuit(EXITSIGHUP);            /* stop all processes */
  1314.     /* NOT REACHED */
  1315.  
  1316. }
  1317.  
  1318.     /* DoWait() -  send SIGCONT to stopped windows, Free dead process windows */
  1319. static
  1320. DoWait()
  1321. {
  1322.     register pid;
  1323.     register struct Layer *layer;
  1324.     union wait wstat;
  1325.     int        i;
  1326.  
  1327.     DO DEBUG("DoWait()\n");
  1328.     while ((pid = wait3 (&wstat, WNOHANG|WUNTRACED, NULL)) > 0)
  1329.         /* dead or stopped child process found */
  1330.         for (i=0; i<MAXPCHAN; i++)
  1331.             if ((layer = &World[i])->lpid == pid)
  1332.               { if (WIFSTOPPED (wstat))
  1333.                   {    /* stopped process so restart it */
  1334.                     /*** DO WE REALLY NEED TO DO THIS? ***/
  1335.                     DO DEBUG("killpg(, SIGCONT)\n");
  1336.                     KillPG(layer, SIGCONT);
  1337.                   }
  1338.                 else
  1339.                   {    /* remove dead process's layer */
  1340.                     DO DEBUG("kill dead process window %d\n", layer->chan);
  1341.                      KillWindow (layer);
  1342.                     /* tell MacLayers layer is dead */
  1343.                     SendDelete(layer->chan);
  1344.                   }
  1345.               }
  1346.  
  1347. } /* DoWait() */
  1348.  
  1349.  
  1350.                 /* KillPG() - send signal to layer's process group */
  1351.  
  1352. static void
  1353. KillPG(layer, signal)
  1354. struct Layer    *layer;                    /* layer to signal */
  1355. int                signal;                    /* signal to send */
  1356. {
  1357.     int            retcode;                /* work variable */
  1358.     int            pgrp;                    /* process group for layer */
  1359.     int            tgrp;                    /* terminal control process group */
  1360.  
  1361.     DO DEBUG("KillPG(%d, sig %d)\n", layer->chan, signal);
  1362.  
  1363.     if (layer->lpid)
  1364.       {    pgrp = getpgrp(layer->lpid);    /* get process group */
  1365.         DO DEBUG("getpgrp() = %d\n", pgrp);
  1366.         if (pgrp != -1)
  1367.           {    retcode = killpg(pgrp, signal);    /* signal it */
  1368.             DO DEBUG("killpg() = %d\n", retcode);
  1369.           }
  1370.  
  1371.         /* After a lot of experimenting it was determined that csh
  1372.         ** creates a new terminal control group when it runs a command.
  1373.         ** Thus the above code failed to forward SIGINT to such commands.
  1374.         ** (Csh would get it but just ignore it.) Thus the following code.
  1375.         */ 
  1376.  
  1377.         /* forward SIGINT to the terminal control group also */
  1378.         if (signal == SIGINT)
  1379.           {    retcode = ioctl(layer->ptyfd, TIOCGPGRP, &tgrp);
  1380.             DO DEBUG("ioctl(ptyfd,TIOCGPGRP) termcntlgrp %d, retcode = %d\n",
  1381.                             tgrp, retcode);
  1382.             /* but only if not the same process group */
  1383.             if (retcode != -1 && tgrp != pgrp)
  1384.               {    retcode = killpg(tgrp, signal);    /* signal it */
  1385.                 DO DEBUG("killpg(%d) = %d\n", tgrp, retcode);
  1386.                 }
  1387.           }
  1388.       }
  1389.  
  1390. } /* KillPG() */
  1391.  
  1392.  
  1393.                 /* KillWindow() - remove a layer from the system */
  1394.  
  1395. /* Note: This function does NOT tell MacLayers about the dead layer */
  1396.  
  1397. static
  1398. KillWindow (layer)
  1399. struct Layer *layer;
  1400. {
  1401.     struct Kbuff    *kb;                /* work buffer free pointer */
  1402.  
  1403.     if (layer->allocated)
  1404.       {                                 /* SHOULD THIS BE SIGKILL ??? */
  1405.         if (layer->lpid)                /* if layer process started ... */
  1406.           {    KillPG(layer, SIGHUP);        /* kill processes */
  1407.             layer->lpid = 0;            /* clear pid field */
  1408.           }
  1409.         RemoveUtmp(layer->slot);
  1410.         (void) chmod(layer->tty, 0666);
  1411.         (void) chown(layer->tty, 0, 0);
  1412.         close(layer->ptyfd);
  1413.         DO DEBUG("chmod/chown %s, SendDelete(%d)\n",layer->tty, layer->chan);
  1414.  
  1415.         ClearShape(&layer->shape);        /* reset the shape structure */
  1416.         /* free all keybuffers but one and reprime it */
  1417.         for (kb=layer->kbuff; kb->next; kb=kb->next)
  1418.             free(kb);                    /* free input buffers */
  1419.         kb->size = 0;                    /* empty buffer */
  1420.         kb->offset = 0;                    /* start refill from front */
  1421.         layer->allocated = 0;            /* window no longer allocated */
  1422.       }
  1423.  
  1424. } /* KillWindow() */
  1425.  
  1426.  
  1427.                     /* FAbort() - signal catcher for quitting */
  1428. static void
  1429. FAbort()
  1430. {
  1431.     DO DEBUG("FAbort()\n");
  1432.     FQuit (EXITSIGQUIT);                /* quit with error exit */
  1433.  
  1434. } /* FAbort() */
  1435.  
  1436.  
  1437.                     /* FQuit() - terminate layers */
  1438. void
  1439. FQuit(exitcode)
  1440. int        exitcode;
  1441. {
  1442.     int            i;
  1443.  
  1444.     DO DEBUG("FQuit(%d)\n",exitcode);
  1445.     for (i=0; i<MAXPCHAN; i++)
  1446.         KillWindow(&World[i]);            /* kill all windows */
  1447.  
  1448.     DO DEBUG("SendQuit()\n");
  1449.     SendQuit();                            /* tell MacLayers to exit layers mode */
  1450.     SetTTY (0, &OldMode);
  1451.     if (RealTtyMode)
  1452.         (void) chmod(RealTtyName, RealTtyMode);    /* restore mode */
  1453.     if (RealSlot)
  1454.         WriteUtmp(RealSlot, &RealUtmp);    /* restore original login */
  1455.     FinitTerm ();
  1456.     sleep(2);                            /* wait for port to reset */
  1457.     printf ("[layers terminated]\n");
  1458.  
  1459.     exit (exitcode);
  1460.  
  1461. } /* FQuit() */
  1462.  
  1463.  
  1464.                     /* MakeWindow() - create new layer */
  1465. static
  1466. MakeWindow (chan, prog, args, dir, lflag, shape)
  1467. int        chan;                            /* zero or channel to use for window */
  1468. char    *prog;
  1469. char     **args;
  1470. char    *dir;
  1471. int        lflag;                            /* one if this to be logged in */
  1472. struct Shape *shape;                    /* shape to use for window */
  1473. {
  1474.     register struct Layer *layer;
  1475.     register char **cp;
  1476.     register f, j;
  1477.     int tf;
  1478.     int mypid;
  1479.     char ebuf[10];
  1480.  
  1481.     DO DEBUG("MakeWindow(%d, %s, %s, dir %s, ",
  1482.                 chan, prog, args[0], dir ? dir : "(none)");
  1483.     DO DEBUG("login %d\n", lflag);
  1484.     DO DEBUG("    origv %d, origh %d, lines %d, chars %d, ",
  1485.                 shape->worigv, shape->worigh, shape->wlines, shape->wchars);
  1486.     DO DEBUG("font %d, attr 0x%x\n", shape->wfont, shape->wattr);
  1487.                     
  1488.     if ((f = OpenPTY ()) == -1)
  1489.       { Msg (0, "No more PTYs.");
  1490.         return ( -1 );
  1491.       }
  1492.  
  1493.     /* if channel not given obtain one from MacLayers */
  1494.     if (chan == 0)
  1495.       {    chan = SendNew(shape);                /* try to get free window */
  1496.         if (chan == 0)
  1497.             {    Msg (0, "No more windows.");
  1498.             return ( -1 );
  1499.             }
  1500.         DO DEBUG("SendNew() == %d\n", chan);
  1501.       }
  1502.  
  1503.     /* verify channel */
  1504.     if (chan <= 0 || chan > MAXPCHAN)
  1505.       {    Msg(0, "Invalid channel %d.", chan);
  1506.         return ( -1 );
  1507.       }
  1508.  
  1509.     /* login this window if it's layer #1 */
  1510.     if (chan == 1)
  1511.         lflag = 1;
  1512.                     
  1513.     if (lflag == -1)
  1514.         lflag = loginflag;
  1515.     
  1516. #ifdef USRLIMIT
  1517.     /*
  1518.      *    Count current number of users, and if logging windows in,
  1519.      */
  1520.     if (lflag == 1)
  1521.       { (void) lseek (utmpf, 0, 0);
  1522.         UserCount = 0;
  1523.         while (read(utmpf, &utmpbuf, sizeof(struct utmp)) > 0)
  1524.           { if (utmpbuf.ut_name[0] != '\0')
  1525.                 UserCount++;
  1526.           }
  1527.         if (UserCount >= USRLIMIT)
  1528.           {    /* MUST NOT ISSUE MESSAGE SINCE IT GETS INTERSPERSED WITH
  1529.             ** PACKET SENT INDICATING CURRENT INPUT WINDOW!! THIS
  1530.             ** CAUSES IT TO BE CORRUPTED.  (1.00 Bug Fix 001)
  1531.             */
  1532.             /* Msg (0, "User limit reached.  Window will not be logged in."); */
  1533.             lflag = 0;
  1534.           }
  1535.       }
  1536. #endif USRLIMIT
  1537.  
  1538.     layer = &World[chan-1];                    /* find layer structure */
  1539.     layer->shape = *shape;                    /* install new window shape */
  1540.  
  1541.     /* ??? What do we do if layer is still active as far as we're concerned? */
  1542.     if (layer->allocated)
  1543.       {    DO DEBUG("??? newlayer not free !!!\n");
  1544.         KillWindow(layer);                    /* kill off old layer */
  1545.         SendDelete(layer->chan);            /* kill window back off */
  1546.         Msg (0, "Makewindow error: Duplicate active layer %d.", chan);
  1547.         return ( -1 );                        /* return failed */
  1548.       }
  1549.  
  1550.     layer->allocated = 1;                    /* show layer now in use */
  1551.     BuildTitle(chan, prog, args);            /* install window title */
  1552.  
  1553.     (void) fcntl (f, F_SETFL, FNDELAY);
  1554.     layer->ptyfd = f;                        /* pseudo pty for task's I/O */
  1555.     layer->ptymask = 1<<f;                    /* set pty device mask */
  1556.     strncpy (layer->cmd, Filename (args[0]), MAXSTR-1);
  1557.     layer->cmd[MAXSTR-1] = '\0';
  1558.     strncpy (layer->tty, TtyName, MAXSTR-1);
  1559.     DO DEBUG("forking %s, tty %s, ptyfd %d, mask %x\n",
  1560.                 layer->cmd, layer->tty, layer->ptyfd, layer->ptymask);
  1561.     (void) chown (TtyName, getuid (), getgid ());
  1562.     if (lflag == 1)
  1563.       { layer->slot = SetUtmp(TtyName, chan == 1);
  1564.         if (chan == 1 && RealTtyMode)
  1565.             /* set to original tty umask */
  1566.             (void) chmod(TtyName, RealTtyMode);
  1567.         else
  1568.             /* force to this mode */
  1569.             (void) chmod(TtyName, TtyMode);
  1570.       }
  1571.     else
  1572.       { layer->slot = -1;
  1573.         /* do not allow any other user access to this device */
  1574.         (void) chmod (TtyName, 0600);
  1575.       }
  1576.     switch (layer->lpid = fork ())
  1577.     { case -1:
  1578.         Msg (errno, "fork");
  1579.         layer->lpid = 0;                    /* clear pid field */
  1580.         return ( -1 );                        /* return failed */
  1581.  
  1582.       case 0:
  1583.         signal (SIGHUP, SIG_DFL);
  1584.         signal (SIGINT, SIG_DFL);
  1585.         signal (SIGQUIT, SIG_DFL);
  1586.         signal (SIGTERM, SIG_DFL);
  1587.         signal (SIGTTIN, SIG_DFL);
  1588.         signal (SIGTTOU, SIG_DFL);
  1589.         signal (SIGALRM, SIG_DFL);
  1590.         setuid (getuid ());
  1591.         setgid (getgid ());
  1592.         if (dir && chdir (dir) == -1)
  1593.           { SendErrorMsg ("Cannot chdir to %s: %s", dir, sys_errlist[errno]);
  1594.             exit (EXITABNORMAL);
  1595.           }
  1596.         mypid = getpid ();
  1597.         ioctl (DevTty, TIOCNOTTY, (char *)0);
  1598.         if ((tf = open (TtyName, O_RDWR)) == -1)
  1599.           { SendErrorMsg ("Cannot open %s: %s", TtyName, sys_errlist[errno]);
  1600.             exit (EXITABNORMAL);
  1601.           }
  1602.         DO DEBUG("Now in new process\n");
  1603.         (void) dup2 (tf, 0);
  1604.         (void) dup2 (tf, 1);
  1605.         (void) dup2 (tf, 2);
  1606.         for (f = getdtablesize () - 1; f > 2; f--)
  1607.             close (f);
  1608.         ioctl (0, TIOCSPGRP, &mypid);
  1609.         (void) setpgrp (0, mypid);
  1610.         SetTTY (0, &OldMode);
  1611.  
  1612.           {    struct    winsize    wsize;        /* window size structure */
  1613.             int            retcode;        /* ioctl return code */
  1614.  
  1615.             wsize.ws_col = layer->shape.wchars; /* character width */
  1616.             wsize.ws_row = layer->shape.wlines; /* window height */
  1617.             wsize.ws_xpixel = 0;                /* necessary? */
  1618.             wsize.ws_ypixel = 0;
  1619.             /* update O/S window state */
  1620.             retcode = ioctl(0, TIOCSWINSZ, &wsize);
  1621.           }
  1622.         (void) umask(Oumask);            /* restore user's original umask */
  1623.         NewEnv[2] = MakeTermcap(layer->shape.wlines, layer->shape.wchars);
  1624.         sprintf (ebuf, "LAYER=%d", chan);
  1625.         NewEnv[3] = ebuf;
  1626.         execvpe (prog, args, NewEnv);
  1627.         printf("%s: cannot exec %s: %s", myname, prog, sys_errlist[errno]);
  1628.         exit (EXITABNORMAL);
  1629.     }
  1630.  
  1631.     return ( chan );
  1632.  
  1633. } /* MakeWindow() */
  1634.  
  1635. static
  1636. execvpe (prog, args, env)
  1637. char *prog, **args, **env;
  1638. {
  1639.     register char *path, *p;
  1640.     char buf[1024];
  1641.     char *shargs[MAXARGS+1];
  1642.     register i;
  1643.     register eaccess = 0;
  1644.  
  1645.     if (prog[0] == '/')
  1646.         path = "";
  1647.     else
  1648.     if ((path = getenv ("PATH")) == 0)
  1649.         path = DefaultPath;
  1650.     do
  1651.       { p = buf;
  1652.         while (*path && *path != ':')
  1653.             *p++ = *path++;
  1654.         if (p > buf)
  1655.             *p++ = '/';
  1656.         strcpy (p, prog);
  1657.         if (*path)
  1658.             ++path;
  1659.         execve (buf, args, env);
  1660.         switch (errno)
  1661.         { case ENOEXEC:
  1662.             shargs[0] = DefaultShell;
  1663.             shargs[1] = buf;
  1664.             for (i = 1; shargs[i+1] = args[i]; ++i);
  1665.             execve (DefaultShell, shargs, env);
  1666.             return;
  1667.  
  1668.           case EACCES:
  1669.             eaccess = 1;
  1670.             break;
  1671.  
  1672.           case ENOMEM: case E2BIG: case ETXTBSY:
  1673.             return;
  1674.  
  1675.         } /* end switch */
  1676.  
  1677.     } while (*path);
  1678.  
  1679.     if (eaccess)
  1680.         errno = EACCES;
  1681.  
  1682. } /* execvpe() */
  1683.  
  1684.  
  1685.                 /* BuildTitle() - create and install window title */
  1686.  
  1687. static void
  1688. BuildTitle(chan, prog, args)
  1689. int            chan;                        /* channel for title */
  1690. char        *prog;                        /* program being executed */
  1691. char        **args;                        /* arg list */
  1692. {
  1693.     int        i;                            /* arg scan index */
  1694.     char    buff[1024];                    /* super huge title buffer */
  1695.  
  1696.     /* skip any leading "/bin/" */
  1697.     if (strncmp(prog, "/bin/", 5) == 0)
  1698.         strcpy(buff, prog+5);            /* leave /bin off */
  1699.     else
  1700.         strcpy(buff, prog);                /* start with program name */
  1701.  
  1702.     /* add all aguments but stop if option ("-") seen */
  1703.     for (i=1; args[i] && args[i][0] != '-'; i++)
  1704.       {    strcat(buff, " ");                /* delimiter */
  1705.         strcat(buff, args[i]);            /* add next parameter */
  1706.       }
  1707.  
  1708.     SendTitle(chan, buff, strlen(buff)); /* set new window title */
  1709.  
  1710. } /* BuildTitle() */
  1711.  
  1712.  
  1713. #ifdef sequent
  1714. static
  1715. OpenPTY ()
  1716. {
  1717.     char *m, *s;
  1718.     register f;
  1719.  
  1720.     f = getpseudotty (&s, &m);
  1721.     strncpy (PtyName, m, sizeof (PtyName));
  1722.     strncpy (TtyName, s, sizeof (TtyName));
  1723.     ioctl (f, TIOCFLUSH, (char *)0);
  1724.     return (f);
  1725. }
  1726.  
  1727. #else
  1728.  
  1729. static
  1730. OpenPTY ()
  1731. {
  1732.     register char *p, *l, *d;
  1733.     register i, f, tf;
  1734.  
  1735.     strcpy (PtyName, PtyProto);
  1736.     strcpy (TtyName, TtyProto);
  1737.     for (p = PtyName, i = 0; *p != 'X'; ++p, ++i);
  1738. #ifndef SEQUENT
  1739.     for (l = "pqrstuvwxyzPQRST"; *p = *l; ++l)
  1740.       { for (d = "0123456789abcdef"; p[1] = *d; ++d)
  1741. #else
  1742.     for (l = "pqrstuvwPQRSTUVW"; *p = *l; ++l)
  1743.       { for (d = "0123456789abcdef"; p[1] = *d; ++d)
  1744. #endif
  1745.           { if ((f = open (PtyName, O_RDWR)) != -1)
  1746.               { TtyName[i] = p[0];
  1747.                 TtyName[i+1] = p[1];
  1748.                 if ((tf = open (TtyName, O_RDWR)) != -1)
  1749.                   { close (tf);
  1750.                     return f;
  1751.                   }
  1752.                 close (f);
  1753.               }
  1754.           }
  1755.       }
  1756.  
  1757.     return -1;
  1758.  
  1759. } /* OpenPTY() */
  1760. #endif
  1761.  
  1762. static
  1763. SetTTY (fd, mp)
  1764. struct mode *mp;
  1765. {
  1766.     ioctl (fd, TIOCSETP, &mp->m_ttyb);
  1767.     ioctl (fd, TIOCSETC, &mp->m_tchars);
  1768.     ioctl (fd, TIOCSLTC, &mp->m_ltchars);
  1769.     ioctl (fd, TIOCLSET, &mp->m_lmode);
  1770.     ioctl (fd, TIOCSETD, &mp->m_ldisc);
  1771.  
  1772. } /* SetTTY() */
  1773.  
  1774. static
  1775. GetTTY (fd, mp)
  1776. struct mode *mp;
  1777. {
  1778.     ioctl (fd, TIOCGETP, &mp->m_ttyb);
  1779.     ioctl (fd, TIOCGETC, &mp->m_tchars);
  1780.     ioctl (fd, TIOCGLTC, &mp->m_ltchars);
  1781.     ioctl (fd, TIOCLGET, &mp->m_lmode);
  1782.     ioctl (fd, TIOCGETD, &mp->m_ldisc);
  1783.  
  1784. } /* GetTTY() */
  1785.  
  1786. static
  1787. SetMode (op, np)
  1788. struct mode *op, *np;
  1789. {
  1790.     *np = *op;
  1791. #if 1
  1792.     if (flowctl)
  1793.       {    np->m_ttyb.sg_flags &= ~(CRMOD|ECHO);
  1794.         np->m_ttyb.sg_flags |= CBREAK | ANYP;
  1795.       }
  1796.     else
  1797.         np->m_ttyb.sg_flags = RAW | ANYP;
  1798. #else
  1799.     np->m_ttyb.sg_flags &= ~(CRMOD|ECHO);
  1800.     np->m_ttyb.sg_flags |= CBREAK | ANYP;
  1801. #endif
  1802.     np->m_tchars.t_intrc = -1;
  1803.     np->m_tchars.t_quitc = -1;
  1804.     if (!flowctl)
  1805.       { np->m_tchars.t_startc = -1;
  1806.         np->m_tchars.t_stopc = -1;
  1807.       }
  1808.     np->m_ltchars.t_suspc = -1;
  1809.     np->m_ltchars.t_dsuspc = -1;
  1810.     np->m_ltchars.t_flushc = -1;
  1811.     np->m_ltchars.t_lnextc = -1;
  1812.  
  1813. } /* SetMode() */
  1814.  
  1815. static char *
  1816. GetTtyName ()
  1817. {
  1818.     int n;
  1819.     char *p;
  1820.  
  1821.     for (p = 0, n = 0; n <= 2 && !(p = ttyname (n)); n++);
  1822.  
  1823.     if (!p || *p == '\0')
  1824.         Msg (0, "layers must run on a tty.");
  1825.  
  1826.     return ( p );
  1827.  
  1828. } /* GetTtyName() */
  1829.  
  1830.  
  1831. static
  1832. Kill (pid, sig)
  1833. {
  1834.     if (pid != 0)
  1835.         (void) kill (pid, sig);
  1836. }
  1837.  
  1838.             /* GetSockName() - set SockName; if LTY env return 1 else 0 */
  1839. static
  1840. GetSockName ()
  1841. {
  1842.     register client;
  1843.     static char buf[2*MAXSTR];
  1844.  
  1845.     if (!mflag && (SockName = getenv ("LTY")) != 0 && *SockName != '\0')
  1846.       { client = 1;
  1847.         setuid (getuid ());
  1848.         setgid (getgid ());
  1849.       }
  1850.     else
  1851.       { sprintf (buf, "%s.%s", HostName, Filename (RealTtyName));
  1852.         SockName = buf;
  1853.         client = 0;
  1854.       }
  1855.     return client;
  1856.  
  1857. } /* GetSockName() */
  1858.  
  1859. static
  1860. MakeServerSocket ()
  1861. {
  1862.     register s;
  1863.     struct sockaddr_un a;
  1864.     char *p;
  1865.  
  1866.     if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) == -1)
  1867.         Msg (errno, "socket");
  1868.     a.sun_family = AF_UNIX;
  1869.     strcpy (SockNamePtr, SockName);
  1870.     strcpy (a.sun_path, SockPath);
  1871.     if (connect (s, (struct sockaddr *)&a, strlen (SockPath)+2) != -1)
  1872.       { p = Filename (SockPath);
  1873.         Msg (0, "You already have a layers running on %s.", p);
  1874.         /*NOTREACHED*/
  1875.       }
  1876.     DO DEBUG("MakeServerSocket: unlink(SockPath)/bind()/chown/listen\n");
  1877.     (void) unlink (SockPath);
  1878.     if (bind (s, (struct sockaddr *)&a, strlen (SockPath)+2) == -1)
  1879.         Msg (errno, "bind");
  1880.     (void) chown (SockPath, getuid (), getgid ());
  1881.     if (listen (s, 5) == -1)
  1882.         Msg (errno, "listen");
  1883.     return s;
  1884.  
  1885. } /* MakeServerSocket() */
  1886.  
  1887. static
  1888. MakeClientSocket (err)
  1889. {
  1890.     register s;
  1891.     struct sockaddr_un a;
  1892.  
  1893.     if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) == -1)
  1894.         Msg (errno, "socket");
  1895.     a.sun_family = AF_UNIX;
  1896.     strcpy (SockNamePtr, SockName);
  1897.     strcpy (a.sun_path, SockPath);
  1898.     if (connect (s, (struct sockaddr *)&a, strlen (SockPath)+2) == -1)
  1899.       { if (err)
  1900.           { Msg (errno, "connect: %s", SockPath); }
  1901.         else
  1902.           { close (s);
  1903.             return -1;
  1904.           }
  1905.       }
  1906.     return s;
  1907.  
  1908. } /* MakeClientSocket() */
  1909.  
  1910. static
  1911. SendCreateMsg (s, ac, av, lflag, shape)
  1912. char **av;
  1913. struct Shape *shape;
  1914. {
  1915.     struct msg m;
  1916.     register char *p;
  1917.     register len, n;
  1918.     char    *pwd;                    /* PWD environment string */
  1919.  
  1920.     DO DEBUG("SendCreateMsg(%d, ac %d, lflag %d\n", s, ac, lflag);
  1921.     m.type = MSG_CREATE;
  1922.     p = m.m.create.line;
  1923.     for (n = 0; ac > 0 && n < MAXARGS-1; ++av, --ac, ++n)
  1924.       { len = strlen (*av) + 1;
  1925.         if (p + len >= m.m.create.line+MAXLINE)
  1926.             break;
  1927.         strcpy (p, *av);
  1928.         p += len;
  1929.       }
  1930.     DO DEBUG("  nargs %d, create line = '%s'\n", n, m.m.create.line);
  1931.     m.m.create.nargs = n;
  1932.     m.m.create.lflag = lflag;
  1933.     m.m.create.shape = *shape;            /* pass window shape */
  1934.  
  1935.     /* Since Suns can hang up on getwd() [damn their stupid networking]
  1936.     ** we try to get the current working directory first from the PWD
  1937.     ** environment variable.
  1938.     */
  1939.     if ((pwd=getenv("PWD")) && strlen(pwd) < 1024)
  1940.         (void) strcpy(m.m.create.dir, pwd);
  1941.     else
  1942.     if (getwd (m.m.create.dir) == 0)
  1943.       {    DO DEBUG("getwd() failed!!\n");
  1944.         Msg (0, "%s", m.m.create.dir);
  1945.       }
  1946.     DO DEBUG("  create.dir = '%s'\n", m.m.create.dir);
  1947.  
  1948.     if (write (s, (char *)&m, sizeof (m)) != sizeof (m))
  1949.       {    DO DEBUG("  write failed!!\n");
  1950.         Msg (errno, "write");
  1951.       }
  1952.     DO DEBUG("SendCreateMsg() done\n");
  1953.  
  1954. } /* SendCreateMsg() */
  1955.  
  1956. /*VARARGS1*/
  1957. static
  1958. SendErrorMsg (fmt, p1, p2, p3, p4, p5, p6)
  1959. char *fmt;
  1960. {
  1961.     register s;
  1962.     struct msg m;
  1963.  
  1964.     s = MakeClientSocket (1);
  1965.     m.type = MSG_ERROR;
  1966.     sprintf (m.m.message, fmt, p1, p2, p3, p4, p5, p6);
  1967.     (void) write (s, (char *)&m, sizeof (m));
  1968.     close (s);
  1969.     sleep (2);
  1970. }
  1971.  
  1972. static
  1973. ReceiveMsg (s)
  1974. {
  1975.     register ns;
  1976.     struct sockaddr_un a;
  1977.     int left, len = sizeof (a);
  1978.     struct msg m;
  1979.     char *p;
  1980.  
  1981.     DO DEBUG ("ReceiveMsg()\n");
  1982.     if ((ns = accept (s, (struct sockaddr *)&a, &len)) == -1)
  1983.       { Msg (errno, "accept");
  1984.         return;
  1985.       }
  1986.     p = (char *)&m;
  1987.     left = sizeof (m);
  1988.     while (left > 0 && (len = read (ns, p, left)) > 0)
  1989.       { p += len;
  1990.         left -= len;
  1991.       }
  1992.     close (ns);
  1993.     if (len == -1)
  1994.         Msg (errno, "read");
  1995.     if (left > 0)
  1996.         return;
  1997.     switch (m.type)
  1998.     { case MSG_CREATE:
  1999.         DO DEBUG("MSG_CREATE:\n");
  2000.         ExecCreate (&m);
  2001.         break;
  2002.  
  2003.       case MSG_ERROR:
  2004.         DO DEBUG("MSG_ERROR:\n");
  2005.         Msg (0, "%s", m.m.message);
  2006.         break;
  2007.  
  2008.       default:
  2009.         Msg (0, "Invalid message (type %d).", m.type);
  2010.  
  2011.     } /* end switch */
  2012.  
  2013. } /* ReceiveMsg() */
  2014.  
  2015. static
  2016. ExecCreate (mp)
  2017. struct msg *mp;
  2018. {
  2019.     char *args[MAXARGS];
  2020.     register n;
  2021.     register char **pp = args, *p = mp->m.create.line;
  2022.  
  2023.     for (n = mp->m.create.nargs; n > 0; --n)
  2024.       { *pp++ = p;
  2025.         p += strlen (p) + 1;
  2026.       }
  2027.     *pp = 0;
  2028.     n = MakeWindow (0, mp->m.create.line, args, mp->m.create.dir,
  2029.                         mp->m.create.lflag, &mp->m.create.shape);
  2030.  
  2031. } /* ExecCreate() */
  2032.  
  2033. #if 0
  2034. static
  2035. ReadRc (fn)
  2036. char *fn;
  2037. {
  2038.     FILE *f;
  2039.     register char *p, **pp, **ap;
  2040.     register argc, num, c;
  2041.     char buf[256];
  2042.     char *args[MAXARGS];
  2043.     int key;
  2044.     struct Shape shape;                        /* shape for new window */
  2045.  
  2046.     ClearShape(&shape);                        /* initialize shape */
  2047.     ap = args;
  2048.     if (access (fn, R_OK) == -1)
  2049.         return;
  2050.     if ((f = fopen (fn, "r")) == NULL)
  2051.         return;
  2052.     while (fgets (buf, 256, f) != NULL)
  2053.       { if (p = rindex (buf, '\n'))
  2054.             *p = '\0';
  2055.         if ((argc = Parse (fn, buf, ap)) == 0)
  2056.             continue;
  2057.         if (strcmp (ap[0], "escape") == 0)
  2058.           { p = ap[1];
  2059.             if (argc < 2 || strlen (p) != 2)
  2060.                 Msg (0, "%s: two characters required after escape.", fn);
  2061.             Esc = *p++;
  2062.             MetaEsc = *p;
  2063.             ktab[Esc].type = KEY_OTHER;
  2064.           }
  2065.         else
  2066.         if (strcmp (ap[0], "login") == 0)
  2067.           { loginflag = 1;
  2068.           }
  2069.         else
  2070.         if (strcmp (ap[0], "unlogin") == 0)
  2071.           { loginflag = 0; }
  2072.         else
  2073.         if (strcmp (ap[0], "nologin") == 0)
  2074.           { loginflag = 0; }
  2075.         else
  2076.         if (strcmp (ap[0], "chdir") == 0)
  2077.            { p = argc < 2 ? home : ap[1];
  2078.             if (chdir (p) == -1)
  2079.             Msg (errno, "%s", p);
  2080.           }
  2081.         else
  2082.         if (strcmp (ap[0], "mode") == 0)
  2083.           { if (argc != 2)
  2084.               { Msg (0, "%s: mode: one argument required.", fn); }
  2085.             else
  2086.             if (!IsNum (ap[1], 7))
  2087.               { Msg (0, "%s: mode: octal number expected.", fn); }
  2088.             else
  2089.                 (void) sscanf (ap[1], "%o", &TtyMode);
  2090.           }
  2091.         else
  2092.         if (strcmp (ap[0], "bell") == 0)
  2093.           { if (argc != 2)
  2094.               { Msg (0, "%s: bell: one argument required.", fn); }
  2095.             else
  2096.               { if ((BellString = malloc (strlen (ap[1]) + 1)) == 0)
  2097.                     Msg (0, "Out of memory.");
  2098.                 istrcpy (BellString, ap[1]);
  2099.               }
  2100.           }
  2101.         else
  2102.         if (strcmp (ap[0], "screen") == 0)
  2103.           { num = 0;
  2104.             if (argc > 1 && IsNum (ap[1], 10))
  2105.               { num = atoi (ap[1]);
  2106.                 if (num < 0 || num > MAXWIN-1)
  2107.                     Msg (0, "%s: illegal screen number %d.", fn, num);
  2108.                 --argc; ++ap;
  2109.               }
  2110.             if (argc < 2)
  2111.               { ap[1] = ShellProg; argc = 2; }
  2112.             ap[argc] = 0;
  2113.             (void) MakeWindow (0, ap[1], ap+1, (char *)0, loginflag, &shape);
  2114.           }
  2115.         else
  2116.         if (strcmp (ap[0], "bind") == 0)
  2117.           { p = ap[1];
  2118.             if (argc < 2 || *p == '\0')
  2119.                 Msg (0, "%s: key expected after bind.", fn);
  2120.             if (p[1] == '\0')
  2121.               { key = *p; }
  2122.             else
  2123.             if (p[0] == '^' && p[1] != '\0' && p[2] == '\0')
  2124.               { c = p[1];
  2125.                 if (isupper (c))
  2126.                     p[1] = tolower (c);    
  2127.                 key = Ctrl(c);
  2128.               }
  2129.             else
  2130.             if (IsNum (p, 7))
  2131.               { (void) sscanf (p, "%o", &key);
  2132.               }
  2133.             else
  2134.               { Msg (0, "%s: bind: character, ^x, or octal number expected.", fn); }
  2135.             ktab[key].lflag = loginflag;
  2136.             if (argc < 3)
  2137.               { ktab[key].type = 0;
  2138.               }
  2139.             else
  2140.               { for (pp = KeyNames; *pp; ++pp)
  2141.                 if (strcmp (ap[2], *pp) == 0) break;
  2142.                 if (*pp)
  2143.                   { ktab[key].type = pp-KeyNames+1; }
  2144.                 else
  2145.                   { ktab[key].type = KEY_CREATE;
  2146.                     ktab[key].args = SaveArgs (argc-2, ap+2);
  2147.                   }
  2148.               }
  2149.           }
  2150.         else
  2151.             Msg (0, "%s: unknown keyword \"%s\".", fn, ap[0]);
  2152.       }
  2153.     (void) fclose (f);
  2154.  
  2155. } /* ReadRc() */
  2156.  
  2157. static
  2158. Parse (fn, buf, args)
  2159. char *fn, *buf, **args;
  2160. {
  2161.     register char *p, **ap;
  2162.     register delim, argc;
  2163.  
  2164.     p = buf;
  2165.     ap = args;
  2166.     argc = 0;
  2167.     for (;;)
  2168.       { while (*p && (*p == ' ' || *p == '\t'))
  2169.             ++p;
  2170.         if (*p == '\0' || *p == '#')
  2171.             return argc;
  2172.         if (argc > MAXARGS-1)
  2173.             Msg (0, "%s: too many tokens.", fn);
  2174.         delim = 0;
  2175.         if (*p == '"' || *p == '\'')
  2176.           { delim = *p; *p = '\0'; ++p; }
  2177.         ++argc;
  2178.         *ap = p; ++ap;
  2179.         while (*p && !(delim ? *p == delim : (*p == ' ' || *p == '\t')))
  2180.             ++p;
  2181.         if (*p == '\0')
  2182.           { if (delim)
  2183.                 Msg (0, "%s: Missing quote.", fn);
  2184.             else
  2185.                 return argc;
  2186.           }
  2187.         *p++ = '\0';
  2188.       }
  2189.  
  2190. } /* Parse() */
  2191.  
  2192. static char **
  2193. SaveArgs (argc, argv)
  2194. register argc;
  2195. register char **argv;
  2196. {
  2197.     register char **ap, **pp;
  2198.  
  2199.     if ((pp = ap = (char **)malloc ((argc+1) * sizeof (char **))) == 0)
  2200.         Msg (0, "Out of memory.");
  2201.     while (argc--)
  2202.       { if ((*pp = malloc (strlen (*argv)+1)) == 0)
  2203.             Msg (0, "Out of memory.");
  2204.         strcpy (*pp, *argv);
  2205.         ++pp; ++argv;
  2206.       }
  2207.     *pp = 0;
  2208.     return ap;
  2209.  
  2210. } /* SaveArgs() */
  2211. #endif
  2212.  
  2213. static
  2214. MakeNewEnv ()
  2215. {
  2216.     register char **op, **np = NewEnv;
  2217.     static char buf[MAXSTR];
  2218.  
  2219.     if (strlen (SockName) > MAXSTR-5)
  2220.         SockName = "?";
  2221.     sprintf (buf, "LTY=%s", SockName);
  2222.     *np++ = buf;
  2223.     *np++ = Term;
  2224.     np += 2;
  2225.     for (op = environ; *op; ++op)
  2226.       { if (np == NewEnv + MAXARGS - 1)
  2227.             break;
  2228.         if (   !IsSymbol (*op, "TERM")
  2229.             && !IsSymbol (*op, "TERMCAP")
  2230.             && !IsSymbol (*op, "LTY")
  2231.            )
  2232.             *np++ = *op;
  2233.       }
  2234.     *np = 0;
  2235.  
  2236. } /* MakeNewEnv() */
  2237.  
  2238. static
  2239. IsSymbol (e, s)
  2240. register char *e, *s;
  2241. {
  2242.     register char *p;
  2243.     register n;
  2244.  
  2245.     for (p = e; *p && *p != '='; ++p);
  2246.     if (*p)
  2247.       { *p = '\0';
  2248.         n = strcmp (e, s);
  2249.         *p = '=';
  2250.         return n == 0;
  2251.       }
  2252.  
  2253.     return 0;
  2254.  
  2255. } /* IsSymbol() */
  2256.  
  2257. /*VARARGS2*/
  2258. Msg (err, fmt, p1, p2, p3, p4, p5, p6)
  2259. char *fmt;
  2260. {
  2261.     char buf[1024];
  2262.     register char *p = buf;
  2263.  
  2264.     sprintf (p, fmt, p1, p2, p3, p4, p5, p6);
  2265.     if (err)
  2266.       { p += strlen (p);
  2267.         if (err > 0 && err < sys_nerr)
  2268.             sprintf (p, ": %s", sys_errlist[err]);
  2269.         else
  2270.             sprintf (p, ": Error %d", err);
  2271.       }
  2272.     if (!Abortonmsg)
  2273.       { /* MakeStatus (buf, curr);*/
  2274.         printf("%s\r\n", buf);
  2275.       } 
  2276.     else
  2277.       { printf ("%s\r\n", buf);
  2278.         if (Resetenvonmsg)
  2279.           {SetTTY (0, &OldMode);
  2280.             if (RealTtyMode)
  2281.                 (void) chmod(RealTtyName, RealTtyMode);    /* restore mode */
  2282.             if (RealSlot)
  2283.                 WriteUtmp(RealSlot, &RealUtmp);    /* restore original login */
  2284.             FinitTerm ();
  2285.           }
  2286.         exit(exitcode);
  2287.       }
  2288.  
  2289. } /* Msg() */
  2290.  
  2291. static char *
  2292. Filename (s)
  2293. char *s;
  2294. {
  2295.     register char *p;
  2296.  
  2297.     p = s + strlen (s) - 1;
  2298.     while (p >= s && *p != '/')
  2299.         --p;
  2300.     return ++p;
  2301.  
  2302. } /* Filename() */
  2303.  
  2304. static
  2305. IsNum (s, base)
  2306. register char *s;
  2307. register base;
  2308. {
  2309.     for (base += '0'; *s; ++s)
  2310.         if (*s < '0' || *s > base)
  2311.             return 0;
  2312.     return 1;
  2313.  
  2314. } /* IsNum() */
  2315.  
  2316.  
  2317. static
  2318. InitUtmp ()
  2319. {
  2320.     if ((utmpf = open (UtmpName, O_RDWR)) == -1)
  2321.       { if (errno != EACCES)
  2322.             Msg (errno, UtmpName);
  2323.         return;
  2324.       }
  2325.     utmp = 1;
  2326.  
  2327. } /* InitUtmp() */
  2328.  
  2329.  
  2330. static int
  2331. FindUtmp(name)
  2332. char *name;
  2333. {
  2334.     register char *p;
  2335.     register struct ttyent *tp;
  2336.     register slot;
  2337.  
  2338.     DO DEBUG("FindUtmp(%s)\n", name);
  2339.     slot = 1;
  2340.     if (!utmp)
  2341.         return 0;
  2342.     if (p = rindex (name, '/'))
  2343.         ++p;
  2344.     else
  2345.         p = name;
  2346.     setttyent ();
  2347.     while (   (tp = getttyent ()) != NULL
  2348.            && strcmp (p, tp->ty_name) != 0
  2349.           )
  2350.         ++slot;
  2351.     if (tp == NULL)
  2352.         return 0;
  2353.  
  2354.     DO DEBUG(" slot %d\n", slot);
  2355.     return slot;
  2356.  
  2357. } /* FindUtmp() */
  2358.  
  2359.  
  2360. static int
  2361. SetUtmp (name, mainlogin)
  2362. char    *name;                            /* tty name */
  2363. int        mainlogin;                        /* this is primary login */
  2364. {
  2365.     register char *p;
  2366.     register slot;
  2367.     struct utmp u;
  2368.  
  2369.     if ((slot=FindUtmp(name)) == 0)
  2370.         return ( 0 );
  2371.  
  2372.     if (p = rindex (name, '/'))
  2373.         ++p;
  2374.     else
  2375.         p = name;
  2376.  
  2377.     strncpy (u.ut_line, p, 8);
  2378.     strncpy (u.ut_name, LoginName, 8);
  2379. #if 1
  2380.     strncpy(u.ut_host,  Filename (RealTtyName), 16); /* host is real tty */
  2381. #else
  2382.     u.ut_host[0] = '\0';
  2383. #endif
  2384.     if (RealSlot && mainlogin)
  2385.         u.ut_time = RealUtmp.ut_time;        /* use original login time */
  2386.     else
  2387.         time (&u.ut_time);
  2388.     (void) lseek (utmpf, (long)(slot * sizeof (u)), 0);
  2389.     (void) write (utmpf, (char *)&u, sizeof (u));
  2390.  
  2391.     return ( slot );
  2392.  
  2393. } /* SetUtmp() */
  2394.  
  2395. static int
  2396. ReadUtmp(slot, entry)
  2397. int        slot;                                /* slot to read */
  2398. struct utmp    *entry;                            /* entry to read into */
  2399. {
  2400.     int        cnt;                            /* return count */
  2401.  
  2402.     if (!utmp)
  2403.         return;                                /* no utmp access */
  2404.  
  2405.     (void) lseek(utmpf, (long)(slot * sizeof(struct utmp)), 0);
  2406.     cnt =  read(utmpf, (char *)entry, sizeof(struct utmp));
  2407.     DO DEBUG("ReadUtmp cnt %d, errno %d, line %.8s, name %.8s, host %.16s\n",
  2408.         cnt, errno, entry->ut_line, entry->ut_name, entry->ut_host);
  2409.  
  2410.     return ( cnt );
  2411.  
  2412. } /* ReadUtmp() */
  2413.  
  2414. static void
  2415. WriteUtmp(slot, entry)
  2416. int        slot;                                /* slot to write */
  2417. struct utmp    *entry;                            /* entry to write from */
  2418. {
  2419.     int        cnt;                            /* write return code */
  2420.  
  2421.     if (!utmp)
  2422.         return;                                /* no utmp access */
  2423.  
  2424.     (void) lseek(utmpf, (long)(slot * sizeof(struct utmp)), 0);
  2425.     cnt = write(utmpf, (char *)entry, sizeof(struct utmp));
  2426.     DO DEBUG("WriteUtmp() slot %d cnt %d line %.8s name %.8s host %.16s\n",
  2427.                 slot, cnt, entry->ut_line, entry->ut_name, entry->ut_host);
  2428.  
  2429. } /* WriteUtmp() */
  2430.  
  2431. static
  2432. RemoveUtmp (slot)
  2433. {
  2434.     struct utmp u;
  2435.  
  2436.     if (slot)
  2437.       { bzero ((char *)&u, sizeof (u));
  2438.         (void) lseek (utmpf, (long)(slot * sizeof (u)), 0);
  2439.         (void) write (utmpf, (char *)&u, sizeof (u));
  2440.       }
  2441.  
  2442. } /* RemoveUtmp() */
  2443.  
  2444. #ifndef GETTTYENT
  2445.  
  2446. static
  2447. setttyent ()
  2448. {
  2449.     struct stat s;
  2450.     register f;
  2451.     register char *p, *ep;
  2452.  
  2453.     if (ttnext)
  2454.       { ttnext = tt;
  2455.         return;
  2456.       }
  2457.     if ((f = open (ttys, O_RDONLY)) == -1 || fstat (f, &s) == -1)
  2458.         Msg (errno, ttys);
  2459.     if ((tt = malloc (s.st_size + 1)) == 0)
  2460.         Msg (0, "Out of memory.");
  2461.     if (read (f, tt, s.st_size) != s.st_size)
  2462.         Msg (errno, ttys);
  2463.     close (f);
  2464.     for (p = tt, ep = p + s.st_size; p < ep; ++p)
  2465.         if (*p == '\n')
  2466.             *p = '\0';
  2467.     *p = '\0';
  2468.     ttnext = tt;
  2469.  
  2470. } /* setttyent() */
  2471.  
  2472. static struct ttyent *
  2473. getttyent ()
  2474. {
  2475.     static struct ttyent t;
  2476.  
  2477.     if (*ttnext == '\0')
  2478.         return NULL;
  2479.     t.ty_name = ttnext + 2;
  2480.     ttnext += strlen (ttnext) + 1;
  2481.     return &t;
  2482.  
  2483. } /* getttyend() */
  2484.  
  2485. #endif
  2486.  
  2487.  
  2488.  
  2489.                     /* FinitTerm() - reset vt100 terminal */
  2490. static void
  2491. FinitTerm ()
  2492. {
  2493.     /* print out termcap 'is' string to reset terminal */
  2494. #if 0
  2495.     /* This string sets scroll region 1-24 and puts cursor at bottom line */
  2496.     printf("\033[1;24r\033[24;1H");
  2497. #endif
  2498.     fflush(stdout);
  2499. }
  2500.  
  2501. static void
  2502. AddCap (s)
  2503. char *s;
  2504. {
  2505.     register n;
  2506.  
  2507.     if (tcLineLen + (n = strlen (s)) > 55)
  2508.       { strcat (Termcap, "\\\n\t:");
  2509.         tcLineLen = 0;
  2510.       }
  2511.     strcat (Termcap, s);
  2512.     tcLineLen += n;
  2513. }
  2514.  
  2515. static char *
  2516. MakeTermcap(lines, chars)
  2517. int        lines;                            /* default window lines */
  2518. int        chars;                            /* default window chars */
  2519. {
  2520.     char buf[1024];
  2521.     register char **pp, *p;
  2522.  
  2523.     strcpy(Termcap, TermcapConst1);        /* start TERMCAP build */
  2524.     strcat(Termcap, UserTerm);            /* fill in User's terminal type */
  2525.     strcat(Termcap, TermcapConst3);        /* finish our own definition */
  2526.  
  2527.     /* add more capabilities depending upon client version */
  2528.     if (Protocollevel > 1)
  2529.         strcat(Termcap, TermcapConst101);
  2530.  
  2531.     if (lines <= 0 || lines > 200)
  2532.         lines = rows;                    /* force default if none or invalid */
  2533.     if (chars <= 0 || chars > 300)
  2534.         chars = cols;                    /* force default if none or invalid */
  2535.  
  2536.     sprintf(buf, "li#%d:co#%d:", lines, chars);
  2537.     AddCap(buf);
  2538.  
  2539.     return ( Termcap );
  2540.  
  2541. } /* MakeTermcap() */
  2542.  
  2543.  
  2544.                 /* DEBUG() - dump output routine */
  2545.  
  2546. void
  2547. DEBUG(format, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8)
  2548. char        *format;
  2549. int            arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8;
  2550. {
  2551.     fprintf(stderr, format, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
  2552. }
  2553. @//E*O*F layers_1.10/layers.c//
  2554. chmod u=rw,g=r,o=r layers_1.10/layers.c
  2555.  
  2556. echo x - layers_1.10/layers.h
  2557. sed 's/^@//' > "layers_1.10/layers.h" <<'@//E*O*F layers_1.10/layers.h//'
  2558. /*             Copyright (C) 1989 by David W. Trissel 
  2559.  *
  2560.  *  Not derived from licensed software.
  2561.  *
  2562.  * Permission is granted to freely use, copy, modify, and redistribute
  2563.  * this software, provided that no attempt is made to gain profit from it,
  2564.  * the author is not construed to be liable for any results of using the
  2565.  * software, alterations are clearly marked as such, and this notice is
  2566.  * not modified.
  2567.  *
  2568.  */
  2569.  
  2570. #define HOSTPROTOCOL    2                    /* current host protocol */
  2571.  
  2572. #define MAXPCHAN    7                        /* maximum layers supported */
  2573.  
  2574. #define MAXSTR        200
  2575. #define    MAXARGS        64
  2576. #define MAXLINE        1024
  2577. #define IOSIZE        800                        /* data gulp handling size */
  2578.  
  2579. /* WARNING - packet sizes must be insured to never match the ESCAPE char */
  2580. #define    ESCAPE        '}'                        /* datalink escape character */
  2581.  
  2582. #define DO         if (Dflag)                    /* for debugging */
  2583.  
  2584. /* miscelaneous common data */
  2585. extern    int    Dflag;                            /* debug dump indicator flag */
  2586. extern    int    Clientversion;                    /* client version number */
  2587. extern    int    Protocollevel;                    /* effective protocol level */
  2588. extern    int    Clientlevel;                    /* client's protocol level */
  2589.  
  2590. /* Shape structure passed between MacLayers and ourselves */
  2591. struct Shape
  2592. {    short    worigv;                            /* verical window bit origin */
  2593.     short    worigh;                            /* horizontal window bit origin */
  2594.     short    wlines;                            /* window height */
  2595.     short    wchars;                            /* window width */
  2596.     short    wfont;                            /* window font size */
  2597.     short    wattr;                            /* window attributes */
  2598. };
  2599.  
  2600. #define Wa_shell    0x01                    /* window is a shell */
  2601.  
  2602.  
  2603.   /* The following modules define the complete protocol/server interface */
  2604.  
  2605.                 /* layers.c */
  2606.  
  2607. extern void FQuit(/* exitcode */);
  2608. extern void ReceiveQuit();
  2609. extern void ReceiveNew(/* chanid, shape */);
  2610. extern void ReceiveDelete(/* chanid */);
  2611. extern void ReceiveSignal(/* chanid, signal */);
  2612. extern void    ReceiveData(/* chanid, buff, cnt */);
  2613. extern void ReceiveReshape(/*chanid, shape */);
  2614. extern void DEBUG(/* format, arg1, arg2, arg3, arg4 */);
  2615.  
  2616.                 /* protocol.c */
  2617.  
  2618. extern int    InitLink();
  2619. extern int    TopChannel();
  2620. extern int    SendNew(/* shape */);
  2621. extern void    SendTitle(/* chan, buff, cnt */);
  2622. extern void SendDelete(/* chan */);
  2623. extern void SendQuit();
  2624. extern void    SendReshape(/* chan, shape */);
  2625. extern void    SendData(/* chan, buff, cnt */);
  2626. extern void    ProcessStreamin();
  2627. @//E*O*F layers_1.10/layers.h//
  2628. chmod u=rw,g=r,o=r layers_1.10/layers.h
  2629.  
  2630. echo x - layers_1.10/layersize.c
  2631. sed 's/^@//' > "layers_1.10/layersize.c" <<'@//E*O*F layers_1.10/layersize.c//'
  2632. /*             Copyright (C) 1989 by David W. Trissel 
  2633.  *
  2634.  *  Not derived from licensed software.
  2635.  *
  2636.  * Permission is granted to freely use, copy, modify, and redistribute
  2637.  * this software, provided that no attempt is made to gain profit from it,
  2638.  * the author is not construed to be liable for any results of using the
  2639.  * software, alterations are clearly marked as such, and this notice is
  2640.  * not modified.
  2641.  *
  2642.  */
  2643.                 /*         All rights reserved.        */
  2644.  
  2645.         /* layersize - update BSD Sun Unix with window size information */
  2646.  
  2647. #include <stdio.h>
  2648. #include <errno.h>
  2649. #include <sys/ioctl.h>
  2650.  
  2651. extern int sys_nerr;
  2652. extern char    *sys_errlist[];
  2653.  
  2654. static void gotsyserr(/* char * */);
  2655. static void goterr(/* char * */);
  2656. static int    getnumber(/* char * */);
  2657.  
  2658.  
  2659.                         /* main() - update BSD window size */
  2660.  
  2661. main(ac, av)
  2662. int            ac;                            /* argument count */
  2663. char        **av;                        /* argument vector */
  2664. {
  2665.     struct winsize wsize;                /* window size structure for ioctl() */
  2666.     char        *ap;                    /* argument scan pointer */
  2667.     int            lines;                    /* new lines value */
  2668.     int            cols;                    /* new columns value */
  2669.  
  2670.     if (--ac != 2)
  2671.         goterr("Missing lines and column options");
  2672.  
  2673.     /* get window size (actually do this to set xpixel and ypixel values) */
  2674.     if (ioctl(0, TIOCGWINSZ, &wsize) == -1)
  2675.         gotsyserr("No window support in host"); /* terminate with message */
  2676.  
  2677.     /* scan looking for -l and -c line and column numeric sizes */
  2678.     lines = cols = 0;                    /* reset values */
  2679.     while (ac > 0)
  2680.       {    ap = *++av;                        /* point to next argument string */
  2681.         if (ac-- > 0 && *ap == '-')        /* if option ... */
  2682.         switch (ap[1])
  2683.         { case 'l':        /* lines */
  2684.             lines = getnumber(&ap[2]);
  2685.             break;
  2686.  
  2687.           case 'c':        /* columns */
  2688.             cols = getnumber(&ap[2]);
  2689.             break;
  2690.  
  2691.           default:
  2692.             goterr("Usupported option"); /* unsupported option */
  2693.             break;
  2694.  
  2695.         } /* end '-' argument */
  2696.         else
  2697.             goterr("Unsupported parameter"); /* unsupported parameter */
  2698.  
  2699.       } /* end while argument vector scan */
  2700.             
  2701.     /* must have both lines and columns */
  2702.     if (lines == 0 || cols == 0)
  2703.         goterr("Must specify both lines and columns");
  2704.  
  2705.     wsize.ws_col = cols;                /* set columns */
  2706.     wsize.ws_row = lines;                /* set lines */
  2707.     /* update the kernel */
  2708.     if (ioctl(0, TIOCSWINSZ, &wsize) == -1)
  2709.         gotsyserr("Failed to update window size"); /* didn't go */
  2710.  
  2711.  
  2712.  
  2713.                 /* goterr() - issue error and terminate */
  2714.  
  2715. static void
  2716. goterr(msg)
  2717. char        *msg;                        /* error message string */
  2718. {
  2719.     printf("%s\n", msg);                /* send error message to user */
  2720.     exit(1);                            /* terminate with error */
  2721.  
  2722. } /* goterr() */
  2723.  
  2724.  
  2725.                 /* gotsyserror() - system error return */
  2726.  
  2727. static void
  2728. gotsyserr(msg)
  2729. char        *msg;                        /* error string */
  2730. {
  2731.     if (errno > 0 && errno < sys_nerr)
  2732.         printf("%s: %s\n", msg, sys_errlist[errno]);
  2733.     else
  2734.         printf("%s: Error %d\n", msg, errno);
  2735.  
  2736.     exit(1);                            /* exit with failure */
  2737.  
  2738. } /* gotsyserr() */
  2739.  
  2740.  
  2741.                     /* getnumber() - parse option number */
  2742.  
  2743. static int
  2744. getnumber(str)
  2745. char        *str;                        /* start of option string */
  2746. {
  2747.     int            n;                        /* number being built */
  2748.  
  2749.     if (str == NULL)
  2750.         goterr("Invalid numeric in option");
  2751.  
  2752.     /* skip any leading delimiters */
  2753.     while (*str && (*str == ' ' || *str == '\t'))
  2754.         str++;
  2755.  
  2756.     for(n=0; *str && *str >= '0' && *str <= '9'; str++)
  2757.         n = n*10 + *str - '0';            /* add next digit in */
  2758.  
  2759.     /* make sure number terminates legally */
  2760.     switch (*str)
  2761.     { case '\0':
  2762.       case ' ':
  2763.       case '\t':
  2764.       case '\n':
  2765.         if (n <= 0 || n > 200)
  2766.             goterr("Number out of range");
  2767.         break;                            /* these are OK */
  2768.  
  2769.       default:
  2770.         goterr("Invalid numeric in option");
  2771.  
  2772.     } /* end switch */
  2773.  
  2774.     return ( n );                        /* return the number */
  2775.  
  2776. } /* getnumber() */
  2777. @//E*O*F layers_1.10/layersize.c//
  2778. chmod u=rw,g=r,o=r layers_1.10/layersize.c
  2779.  
  2780. echo x - layers_1.10/layertitle.c
  2781. sed 's/^@//' > "layers_1.10/layertitle.c" <<'@//E*O*F layers_1.10/layertitle.c//'
  2782. /*             Copyright (C) 1989 by David W. Trissel
  2783.  *
  2784.  *  Not derived from licensed software.
  2785.  *
  2786.  * Permission is granted to freely use, copy, modify, and redistribute
  2787.  * this software, provided that no attempt is made to gain profit from it,
  2788.  * the author is not construed to be liable for any results of using the
  2789.  * software, alterations are clearly marked as such, and this notice is
  2790.  * not modified.
  2791.  *
  2792.  */
  2793.                 /*         All rights reserved.        */
  2794.  
  2795.             /* layertitle - utility to specify window title */
  2796.  
  2797. #include <stdio.h>
  2798.  
  2799. #define ESC 0x1b
  2800.  
  2801.             /* main() - send string designating layers window title */
  2802.  
  2803. main(ac, av)
  2804. int         ac;                         /* argument count */
  2805. char        **av;                       /* argument vector */
  2806. {
  2807.     char        *ap;                    /* argument scan pointer */
  2808.  
  2809.     if (--ac != 1)
  2810.       { printf("usage: layertitle \"new window title\"\n");
  2811.         exit(1);
  2812.       }
  2813.        
  2814.     ap = *++av;                         /* point to argument string */
  2815.  
  2816.     /* Transmit the title string in the ANSI Private Message format
  2817.     ** which is
  2818.     **              ESC '^' message ESC '\'
  2819.     */
  2820.     printf("%c%c%s%c%c", ESC, '^', ap, ESC, '\\');
  2821.  
  2822. }  /* main() */
  2823. @//E*O*F layers_1.10/layertitle.c//
  2824. chmod u=rw,g=r,o=r layers_1.10/layertitle.c
  2825.  
  2826. echo x - layers_1.10/macbput.1
  2827. sed 's/^@//' > "layers_1.10/macbput.1" <<'@//E*O*F layers_1.10/macbput.1//'
  2828. @.TH MACBPUT local "17 Mar 1990"
  2829. @.UC 4
  2830. @.SH NAME
  2831. macbput \- send file to macintosh via macbinary protocol
  2832. @.SH SYNOPSIS
  2833. @.B macbput
  2834. file
  2835. @.br
  2836. @.B macbput
  2837. [
  2838. @.B \-rdu
  2839. ] file
  2840. [
  2841. @.B \-t
  2842. type
  2843. ]
  2844. [
  2845. @.B \-c
  2846. owner
  2847. ]
  2848. [
  2849. @.B \-n
  2850. name
  2851. ]
  2852. @.SH DESCRIPTION
  2853. @.I Macbput
  2854. sends a file to a Macintosh running MacTerminal.
  2855. The File Transfer Protocol settings should specify the "MacBinary"
  2856. transfer method.
  2857. Macbput will also work with other communications programs for the Mac
  2858. (e.g. MacLayers);
  2859. consult the user's manual for your macbinary-compatable communications
  2860. program for more information.
  2861. This manual page will only address the use of macbput with MacTerminal.
  2862. @.PP
  2863. To use this program, log into the unix system using MacTerminal,
  2864. and run macbput specifying the desired options and one file to be sent.
  2865. If MacTerminal is properly configured, it will recognize that a file
  2866. is arriving on the serial line and put up an indicator showing how
  2867. much of the file has been sent.
  2868. Several Control-X's may be used to force macbput
  2869. to give up if the transfer fails.
  2870. @.PP
  2871. If none of the
  2872. @.B \-rdu
  2873. flags are specified,
  2874. @.I macbput
  2875. sends three unix files to the Mac:
  2876. @.IB file .info ,
  2877. @.IB file .data ,
  2878. and
  2879. @.IB file .rsrc .
  2880. These specify the three parts of one Mac file:  the .data file
  2881. becomes the data fork, the .rsrc file becomes the resource fork,
  2882. and the .info file specifies the sizes of the two forks, as well
  2883. as the file name, file type, creation date, and other information.
  2884. This is useful for returning files to the Mac which were stored
  2885. using macget or macbget.
  2886. @.PP
  2887. The
  2888. @.B \-r
  2889. flag specifies
  2890. @.I resource
  2891. mode.
  2892. Either
  2893. @.IB file .rsrc
  2894. or
  2895. @.I file
  2896. will be sent to the Mac, along with a forged
  2897. @.B .info
  2898. file and an empty
  2899. @.B .data
  2900. file.
  2901. The file sent becomes the resource fork of the Mac file.
  2902. @.PP
  2903. The
  2904. @.B \-d
  2905. flag specifies
  2906. @.I data
  2907. mode.
  2908. Either
  2909. @.IB file .data
  2910. ,
  2911. @.IB file .text
  2912. or
  2913. @.I file
  2914. will be sent to the Mac, along with a forged
  2915. @.B .info
  2916. file and an empty
  2917. @.B .rsrc
  2918. file.
  2919. The file sent becomes the data fork of the Mac file.
  2920. @.PP
  2921. The
  2922. @.B \-u
  2923. flag requests
  2924. @.I unix
  2925. mode, which is the same as
  2926. @.I data
  2927. mode except unix newline characters are converted
  2928. into carriage returns.
  2929. Human-readable unix text files sent to the Mac using this option
  2930. will be compatible with applications which expect "text only" files.
  2931. @.PP
  2932. The remaining options serve to override the default
  2933. file type, owner, and file name to be used on the Mac.
  2934. The default type and owner for
  2935. @.I resource
  2936. and
  2937. @.I data
  2938. mode defaults are "????", "????", and
  2939. @.I unix
  2940. mode defaults are "TEXT" and "MACA".
  2941. @.SH SEE ALSO
  2942. macput(local), macget(local), xbin(local), macbin(local), mcvert(local)
  2943. @.SH BUGS
  2944. The macbinary protocol may not work over flow controlled communication lines,
  2945. some terminal concentrators, or when using rlogin.
  2946. @.SH FEATURES
  2947. Properly initializes the Creation Date.
  2948. @.SH AUTHOR
  2949. Original base code: Dave Johnson, Brown 7/31/84
  2950. @//E*O*F layers_1.10/macbput.1//
  2951. chmod u=rw,g=r,o=r layers_1.10/macbput.1
  2952.  
  2953. echo x - layers_1.10/macbput.c
  2954. sed 's/^@//' > "layers_1.10/macbput.c" <<'@//E*O*F layers_1.10/macbput.c//'
  2955. /*
  2956.  *    macbput.c
  2957.  *
  2958.  *    This is a modified version of Dave Johnson's macput (see Copyright
  2959.  *    below) intended for use with MacLayers v1.20
  2960.  */
  2961.  
  2962.  
  2963. /*
  2964.  * (originally macput) -- send file to Macintosh using MacBinary XMODEM protocol
  2965.  * Dave Johnson, Brown University Computer Science
  2966.  *
  2967.  * (c) 1984 Brown University 
  2968.  * may be used but not sold without permission
  2969.  *
  2970.  */
  2971.  
  2972. /* To compile:    
  2973.                   cc -O -o macbput macbput.c
  2974.     (Sun 4.2 BSD) cc -O -DSUNBSD42 -o macbput macbput.c
  2975.     (System V)    cc -O -DSYSV -o macbput macbput.c
  2976.  
  2977.    Latest modification 1/93 by Eric Rosen
  2978.     to be used with MacLayers v1.20
  2979.  
  2980.  1. inserted pad byte to be compatible with THINK C's word alignment
  2981.     requirements in header; also added identification character as
  2982.     temporary hack for version control
  2983.  
  2984.  2. inserted helpful examples in the usage string when no arguments
  2985.     are given
  2986.  
  2987.  
  2988.    Latest modification 4/27/91 by Trissel-
  2989.  
  2990.  1. Original code was absolutely pathetic recovering from noise on the
  2991.     line. In many cases noise on the line would cause program to either
  2992.     hang indefinetly or abort instantly. The code to examine responses
  2993.     has been enhanced to overcome these limitations.
  2994.  
  2995.  
  2996.    Modification  4/17/91 by Trissel -
  2997.  
  2998.  1. ??? XMODEM block count not fixed in official MacLayers Release???
  2999.     Point 4 below claims that it was, however the code obviously does NOT
  3000.     increment the last block count of the data fork if the data fork is
  3001.     not an even multiple of 128 bytes in size.
  3002.  
  3003.    Modifications 10/20/88 by Trissel -
  3004.  
  3005.  1. General cleanup by removal of unused definitions and headers.
  3006.  2. Added #ifdefs to support System V and BSD 4.2 Sun compilation.
  3007.  3. Removed ancient Macterminal Beta 0.5X code.
  3008.  4. Fixed bad bug where XMODEM block count was not bumped up
  3009.     after the first fork transfer.
  3010.  
  3011.     Dave Trissel
  3012.     Motorola Inc.
  3013.     ut-sally!oakhill!davet
  3014.  
  3015.    This code is fundamentally from two earlier programmers:
  3016.  
  3017.     Jon Hueras
  3018.     Symantec/THINK Technologies
  3019.     singer@endor.harvard.edu
  3020.  
  3021.     who added 2-Byte CRC capability to code from:
  3022.  
  3023.     Dave Johnson
  3024.     ddj%brown@csnet-relay.arpa
  3025.     Brown University Computer Science
  3026.  
  3027.    who did the initial MacTerminal 1.1 transfer protocol.
  3028. */
  3029.  
  3030. /* If you have System V define the following: */
  3031.     /* #define SYSV */
  3032.  
  3033. /* Sun BSD 4.2 systems should define the following: */
  3034.     /* #define SUNBSD42 */
  3035.  
  3036. #include <stdio.h>
  3037. #include <signal.h>
  3038. #include <setjmp.h>
  3039. #ifdef SYSV
  3040. #include <termio.h>
  3041. #else
  3042. #include <sgtty.h>
  3043. #endif
  3044. #include <sys/types.h>
  3045. #include <sys/stat.h>
  3046.  
  3047. #ifdef SUNBSD42
  3048. /* RAW is no longer being found on latest Sun system (??) (Trissel) */
  3049. #define RAW 0x20
  3050. #endif
  3051.  
  3052. #define RECORDBYTES 132
  3053. #define DATABYTES 128
  3054. #define NAMEBYTES 64
  3055.  
  3056. #define RETRIES 10
  3057. #define ACKTIMO 10
  3058. #define FLUSHTIMO 2
  3059.  
  3060. #define MAXRECNO 0xff
  3061. #define BYTEMASK 0xff
  3062.  
  3063. #define TMO -1
  3064. #define DUP '\000'
  3065. #define SOH '\001'
  3066. #define EOT '\004'
  3067. #define ACK '\006'
  3068. #define NAK '\025'
  3069. #define CAN '\030'
  3070. #define EEF '\032'
  3071. #define ESC '\033'
  3072.  
  3073. #define H_NLENOFF 1
  3074. #define H_NAMEOFF 2
  3075. /* 65 <-> 80 is the FInfo structure */
  3076. #define H_TYPEOFF 65
  3077. #define H_AUTHOFF 69
  3078.  
  3079. #define H_LOCKOFF 81
  3080. #define H_DLENOFF 83
  3081. #define H_RLENOFF 87
  3082. #define H_CTIMOFF 91
  3083. #define H_MTIMOFF 95
  3084.  
  3085. #define H_OLD_DLENOFF 81
  3086. #define H_OLD_RLENOFF 85
  3087.  
  3088. #define TEXT 0
  3089. #define DATA 1
  3090. #define RSRC 2
  3091. #define FULL 3
  3092.  
  3093. int mode, txtmode;
  3094.  
  3095. struct macheader {
  3096.     char m_name[NAMEBYTES+1];
  3097.     char m_type[4];
  3098.     char m_author[4];
  3099.     long m_datalen;
  3100.     long m_rsrclen;
  3101.     long m_createtime;
  3102.     long m_modifytime;
  3103. } mh;
  3104.  
  3105. struct filenames {
  3106.     char f_info[256];
  3107.     char f_data[256];
  3108.     char f_rsrc[256];
  3109. } files;
  3110.  
  3111. int recno, crc;
  3112. char buf[DATABYTES];
  3113.  
  3114. char usage[] =
  3115.     "macbput v1.20\nusage: \"macbput [-rdu] [-t type] [-c creator] [-n name] filename\"\n";
  3116.  
  3117. main(ac, av)
  3118. char **av;
  3119. {
  3120.     int n;
  3121.     char *filename;
  3122.  
  3123.     if (ac == 1) {
  3124.         fprintf(stderr, usage);
  3125.         fprintf(stderr, "Eg:\n\tTo send a binary file:\n");
  3126.         fprintf(stderr, "\n\t\tmacbput -d filename\n");
  3127.         fprintf(stderr, "\n\tTo send a text file:\n");
  3128.         fprintf(stderr, "\n\t\tmacbput -d filename -t TEXT\n");
  3129.         exit(1);
  3130.     }
  3131.  
  3132.     mode = FULL;
  3133.     ac--; av++;
  3134.     while (ac) {
  3135.         if (av[0][0] == '-') {
  3136.             switch (av[0][1]) {
  3137.             case 'r':
  3138.                 mode = RSRC;
  3139.                 strncpy(mh.m_type, "????", 4);
  3140.                 strncpy(mh.m_author, "????", 4);
  3141.                 break;
  3142.             case 'u':
  3143.                 mode = TEXT;
  3144.                 strncpy(mh.m_type, "TEXT", 4);
  3145.                 strncpy(mh.m_author, "MACA", 4);
  3146.                 break;
  3147.             case 'd':
  3148.                 mode = DATA;
  3149.                 strncpy(mh.m_type, "????", 4);
  3150.                 strncpy(mh.m_author, "????", 4);
  3151.                 break;
  3152.             case 'n':
  3153.                 if (ac > 1) {
  3154.                     ac--; av++;
  3155.                     n = strlen(av[0]);
  3156.                     if (n > NAMEBYTES) n = NAMEBYTES;
  3157.                     strncpy(mh.m_name, av[0], n);
  3158.                     mh.m_name[n] = '\0';
  3159.                     break;
  3160.                 }
  3161.                 else goto bad_usage;
  3162.             case 't':
  3163.                 if (ac > 1) {
  3164.                     ac--; av++;
  3165.                     strncpy(mh.m_type, av[0], 4);
  3166.                     break;
  3167.                 }
  3168.                 else goto bad_usage;
  3169.             case 'c':
  3170.                 if (ac > 1) {
  3171.                     ac--; av++;
  3172.                     strncpy(mh.m_author, av[0], 4);
  3173.                     break;
  3174.                 }
  3175.                 else goto bad_usage;
  3176.             default:
  3177. bad_usage:
  3178.                 fprintf(stderr, usage);
  3179.                 exit(1);
  3180.             }
  3181.         }
  3182.         else {
  3183.             filename = av[0];
  3184.         }
  3185.         ac--; av++;
  3186.     }
  3187.  
  3188.     setup_tty();
  3189.     find_files(filename, mode);
  3190.     if (mode != FULL)
  3191.         forge_info();
  3192.  
  3193.     if (send_sync()) {
  3194.         recno = 1;
  3195.         txtmode = 0;
  3196.         send_file(files.f_info, 1, '*');
  3197.  
  3198.         if (mode != FULL)
  3199.             unlink(files.f_info);
  3200.  
  3201.         if (mode == TEXT) txtmode++;
  3202.         send_file(files.f_data, 1, '\0');
  3203.  
  3204.         txtmode = 0;
  3205.         send_file(files.f_rsrc, 0, '\0');
  3206.     }
  3207.     reset_tty();
  3208. }
  3209.  
  3210. find_files(filename, mode)
  3211. char *filename;
  3212. {
  3213.     int n, tdiff;
  3214.     struct stat stbuf;
  3215.  
  3216.     sprintf(files.f_data, "%s.data", filename);
  3217.     sprintf(files.f_rsrc, "%s.rsrc", filename);
  3218.  
  3219.     if (mode == FULL) {
  3220.         sprintf(files.f_info, "%s.info", filename);
  3221.         if (stat(files.f_info, &stbuf) != 0) {
  3222.             perror(files.f_info);
  3223.             cleanup(-1);
  3224.         }
  3225.         return;
  3226.     }
  3227.     else {
  3228.         strcpy(files.f_info, "#machdrXXXXXX");
  3229.         mktemp(files.f_info);
  3230.     }
  3231.  
  3232.     if (mode == RSRC) {
  3233.         strcpy(files.f_data, "/dev/null");
  3234.         if (stat(files.f_rsrc, &stbuf) != 0) {
  3235.             strcpy(files.f_rsrc, filename);
  3236.             if (stat(files.f_rsrc, &stbuf) != 0) {
  3237.                 perror(files.f_rsrc);
  3238.                 cleanup(-1);
  3239.             }
  3240.         }
  3241.         mh.m_datalen = 0;
  3242.         mh.m_rsrclen = stbuf.st_size;
  3243.     }
  3244.     else {
  3245.         strcpy(files.f_rsrc, "/dev/null");
  3246.         if (stat(files.f_data, &stbuf) != 0) {
  3247.             sprintf(files.f_data, "%s.text", filename);
  3248.             if (stat(files.f_data, &stbuf) != 0) {
  3249.                 strcpy(files.f_data, filename);
  3250.                 if (stat(files.f_data, &stbuf) != 0) {
  3251.                     perror(files.f_data);
  3252.                     cleanup(-1);
  3253.                 }
  3254.             }
  3255.         }
  3256.         mh.m_datalen = stbuf.st_size;
  3257.         mh.m_rsrclen = 0;
  3258.     }
  3259.  
  3260.     if (mh.m_name[0] == '\0') {
  3261.         n = strlen(filename);
  3262.         if (n > NAMEBYTES) n = NAMEBYTES;
  3263.         strncpy(mh.m_name, filename, n);
  3264.         mh.m_name[n] = '\0';
  3265.     }
  3266. }
  3267.  
  3268. forge_info()
  3269. {
  3270.     int n;
  3271.     char *np;
  3272.     FILE *fp;
  3273.  
  3274.     for (np = mh.m_name; *np; np++)
  3275.         if (*np == '_') *np = ' ';
  3276.  
  3277.     buf[H_NLENOFF] = n = np - mh.m_name;
  3278.     strncpy(buf + H_NAMEOFF, mh.m_name, n);
  3279.     strncpy(buf + H_TYPEOFF, mh.m_type, 4);
  3280.     strncpy(buf + H_AUTHOFF, mh.m_author, 4);
  3281.     put4(buf + H_DLENOFF, mh.m_datalen);
  3282.     put4(buf + H_RLENOFF, mh.m_rsrclen);
  3283.     put4(buf + H_CTIMOFF, mh.m_createtime);
  3284.     put4(buf + H_MTIMOFF, mh.m_modifytime);
  3285.     fp = fopen(files.f_info, "w");
  3286.     if (fp == NULL) {
  3287.         perror("temp file");
  3288.         cleanup(-1);
  3289.     }
  3290.     fwrite(buf, 1, DATABYTES, fp);
  3291.     fclose(fp);
  3292. }
  3293.  
  3294. send_sync()
  3295.     {
  3296.         int c;
  3297.         
  3298.         tputc(ESC);
  3299.         tputc('b');
  3300.  
  3301.         for (;;) {
  3302.  
  3303.             if ((c = tgetc(ACKTIMO)) == TMO)
  3304.               {
  3305.                 return(0);
  3306.                 }
  3307.  
  3308.             if (c == NAK)
  3309.               {
  3310.                 return(1);
  3311.                 }
  3312.  
  3313.             if (c == 'C') {
  3314.                 crc++;
  3315.                 return(1);
  3316.             }
  3317.         }
  3318.     }
  3319.  
  3320. send_file(fname, more, id)
  3321. char *fname;
  3322. int more;
  3323. char id;
  3324. {
  3325.     register int status, i, n;
  3326.     FILE *inf;
  3327.  
  3328.     inf = fopen(fname, "r");
  3329.     if (inf == NULL) {
  3330.         perror(fname);
  3331.         cleanup(-1);
  3332.     }
  3333.     for (;;) {
  3334.         n = fread(buf, 1, DATABYTES, inf);
  3335.         if (id == '*') {
  3336.             buf[0] = id;
  3337.             for (i=127; i>65; i--)
  3338.                 buf[i] = buf[i-1];    /* hack */
  3339.         }
  3340.         if (n > 0) {
  3341.             for (i = 0; i < RETRIES; i++) {
  3342.                 send_rec(buf, DATABYTES);
  3343.                 status = tgetc(ACKTIMO);
  3344.                 if (   status != ACK
  3345.                     && status != NAK
  3346.                     && status != CAN
  3347.                     && status != TMO
  3348.                     && status != EOT
  3349.                    )
  3350.                   {    /* We got unknown response - assume noise on the line
  3351.                     ** and flush it. Treat this as a timeout.
  3352.                     */
  3353.  
  3354.                     /* Note: the FLUSHTIMO must be short, otherwise we
  3355.                     ** would flush past the (presumed) noise burst and
  3356.                     ** possibly miss a CAN which would leave the program
  3357.                     ** timing out while the user wonders what happened.
  3358.                     ** (Missing anything else is no big deal since we
  3359.                     ** are going to retry anyway.)
  3360.                     */
  3361.                     while ((status=tgetc(FLUSHTIMO)) != TMO)
  3362.                         ;
  3363.                     /* leave status == TMO */
  3364.                   }
  3365.  
  3366.                 /* exit retry loop if not to resend */
  3367.                 if (status == ACK || status == EOT || status == CAN)
  3368.                     break;
  3369.             } 
  3370.             if (status != ACK) {
  3371.                 /* we are to terminate */
  3372.                 fclose(inf);
  3373.                 cleanup(-1);
  3374.                 /* NOTREACHED */
  3375.             }
  3376.  
  3377.             /* FIX (d.t.) recno always increments for any block sent out */
  3378.             recno++;                /* FIX  d.t. */
  3379.             recno &= MAXRECNO;        /* FIX  d.t. */
  3380.         }
  3381.         if (n < DATABYTES) {
  3382.             if (!more) {
  3383.                 tputc(EOT);
  3384.                 tgetc(ACKTIMO);
  3385.             }
  3386.             return;
  3387.         }
  3388.     }
  3389. }
  3390.  
  3391. send_rec(buf, recsize)
  3392. char buf[];
  3393. int recsize;
  3394. {
  3395.     int i, cksum;
  3396.     char *bp;
  3397.  
  3398.     if (txtmode || !crc) {
  3399.         cksum = 0;
  3400.         bp = buf;
  3401.         for (i = 0; i < recsize; i++, bp++) {
  3402.             if (txtmode && *bp == '\n')
  3403.                 *bp = '\r';
  3404.             cksum += *bp;
  3405.         }
  3406.     }
  3407.  
  3408.     if (crc)
  3409.         cksum = calcrc(buf, recsize);
  3410.  
  3411.     tputc(SOH);
  3412.     tputc((char) recno);
  3413.     tputc((char) (MAXRECNO - recno));
  3414.     tputrec(buf, recsize);
  3415.     
  3416.     if (crc) {
  3417.         tputc((char) (cksum >> 8));
  3418.         tputc((char) cksum);
  3419.     } else
  3420.         tputc((char) cksum);
  3421. }
  3422.  
  3423. static int ttyfd;
  3424. static FILE *ttyf;
  3425. static jmp_buf timobuf;
  3426.  
  3427. tgetc(timeout)
  3428. int timeout;
  3429. {
  3430.     int c;
  3431.  
  3432.     if (setjmp(timobuf))
  3433.         return TMO;
  3434.  
  3435.     alarm(timeout);
  3436.     c = getc(ttyf);
  3437.     alarm(0);
  3438.  
  3439.     if (c == -1)    /* probably hung up or logged off */
  3440.         return EOT;
  3441.     else
  3442.         return c & BYTEMASK;
  3443. }
  3444.  
  3445. tputrec(buf, count)
  3446. char *buf;
  3447. int count;
  3448. {
  3449.     write(ttyfd, buf, count);
  3450. }
  3451.  
  3452. tputc(c)
  3453. char c;
  3454. {
  3455.     write(ttyfd, &c, 1);
  3456. }
  3457.  
  3458. timedout()
  3459. {
  3460.     signal(SIGALRM, timedout);    /* for pre-4.2 systems */
  3461.     longjmp(timobuf, 1);
  3462. }
  3463.  
  3464. #ifdef SYSV
  3465. static struct termio otty, ntty;
  3466. #else
  3467. static struct sgttyb otty, ntty;
  3468. #endif
  3469.  
  3470. /* should turn messages off */
  3471.  
  3472. setup_tty()
  3473. {
  3474.     int cleanup();
  3475.     int timedout();
  3476.  
  3477.     ttyf = stdin;
  3478.     ttyfd = fileno(stdout);
  3479. #ifdef SYSV
  3480.     ioctl(ttyfd, TCGETA, &otty);        /* get termio info */
  3481. #else
  3482.     ioctl(ttyfd, TIOCGETP, &otty);
  3483. #endif
  3484.     signal(SIGHUP, cleanup);
  3485.     signal(SIGINT, cleanup);
  3486.     signal(SIGQUIT, cleanup);
  3487.     signal(SIGTERM, cleanup);
  3488.     signal(SIGALRM, timedout);
  3489.     ntty = otty;
  3490. #ifdef SYSV
  3491.     ntty.c_iflag = BRKINT;                /* only interrupt on break */
  3492.     ntty.c_oflag = 0;                    /* no output processing */
  3493.     ntty.c_cflag |= CS8;                /* 8 bit characters */
  3494.     ntty.c_lflag = 0;                    /* no echoing */
  3495.     ntty.c_cc[VEOF] = 1;                /* "MIN" minimum chars before input */
  3496.     ntty.c_cc[VEOL] = 1;                /* "TIME" maximum .1 secs before feed */
  3497.     ioctl(ttyfd, TCSETAF, &ntty);        /* set mode and flush input */
  3498. #else
  3499.     ntty.sg_flags = RAW;
  3500.     ioctl(ttyfd, TIOCSETP, &ntty);
  3501. #endif
  3502. }
  3503.  
  3504. reset_tty()
  3505. {
  3506.     if (ttyf != NULL) {
  3507. #ifdef SYSV
  3508.         ioctl(ttyfd, TCSETAF, &otty);    /* reset after output drains */
  3509. #else
  3510.         sleep (5);                        /* wait for output to drain */
  3511.         ioctl(ttyfd, TIOCSETP, &otty);
  3512. #endif
  3513.     }
  3514. }
  3515.  
  3516. cleanup(sig)
  3517. int sig;
  3518. {
  3519.     reset_tty();
  3520.     exit(sig);
  3521. }
  3522.  
  3523. put4(bp, value)
  3524. char *bp;
  3525. long value;
  3526. {
  3527.     register int i, c;
  3528.  
  3529.     for (i = 0; i < 4; i++) {
  3530.         c = (value >> 24) & BYTEMASK;
  3531.         value <<= 8;
  3532.         *bp++ = c;
  3533.     }
  3534. }
  3535.  
  3536. int calcrc(ptr,    count)
  3537. char *ptr;
  3538. int count;
  3539.     {
  3540.         int    crc, i;
  3541.  
  3542.         crc    = 0;
  3543.         while (--count >= 0) {
  3544.          crc ^= ((int) *ptr++) << 8;
  3545.          for (i = 0; i < 8; ++i)
  3546.                  if (crc & 0x8000)
  3547.              crc = crc <<    1 ^ 0x1021;
  3548.                  else
  3549.              crc <<= 1;
  3550.          }
  3551.         return (crc    & 0xFFFF);
  3552.     }
  3553. @//E*O*F layers_1.10/macbput.c//
  3554. chmod u=rw,g=r,o=r layers_1.10/macbput.c
  3555.  
  3556. echo x - layers_1.10/macbput.h
  3557. sed 's/^@//' > "layers_1.10/macbput.h" <<'@//E*O*F layers_1.10/macbput.h//'
  3558. /**
  3559. ***                Copyright (C) 1991 by David W. Trissel
  3560. ***
  3561. ***                  Not derived from licensed software.
  3562. ***
  3563. *** Permission is granted to freely use, copy, modify, and redistribute
  3564. *** this software, provided that no attempt is made to gain profit from it,
  3565. *** the author is not construed to be liable for any results of using the
  3566. *** software, alterations are clearly marked as such, and this notice is
  3567. *** not modified.
  3568. ***
  3569.  
  3570. #define RECORDBYTES 132                /* complete XMODEM block length */
  3571. #define DATABYTES 128                /* data portion of block length */
  3572. #define NAMEBYTES 63                /* max file name size in info block */
  3573.  
  3574. #define RETRIES 10                    /* max number of error retries */
  3575. #define ACKTIMO 10                    /* seconds timeout waiting for ACK */
  3576. #define FLUSHTIMO 2                    /* Flush timeout when invalid response
  3577.                                     ** recieved, must be very short. Note:
  3578.                                     ** a one (1) may not work because timer
  3579.                                     ** will trip between 0 and 1 sec. */
  3580.  
  3581. #define MAXRECNO 0xff                /* top modulo record number */
  3582. #define BYTEMASK 0xff                /* single byte mask for integers */
  3583.  
  3584. #define TMO -1                        /* timeout function return value */
  3585. #define SOH    0x01                    /* ANSI Start Of Header */
  3586. #define EOT 0x04                    /* ANSI End Of Transmission */
  3587. #define ACK 0x06                    /* ANSI positive ACKnowledge */
  3588. #define NAK 0x15                    /* ANSI Negative AcKnowledge */
  3589. #define CAN 0x18                    /* ANSI CANcel */
  3590. #define ESC 0x1b                    /* ANSI ESCape */
  3591.  
  3592.     /* Definition of the 128 byte Mac file info record */
  3593. #define H_VEROFF    0                /* Mac OS only supports version zero */
  3594. #define H_NLENOFF    1                /* Mac file name length (1..63) */
  3595. #define H_NAMEOFF    2                /* Mac file name */
  3596.  /* 65 <-> 80 is the FInfo structure */
  3597. #define H_TYPEOFF    65                /* file type */
  3598. #define H_AUTHOFF    69                /* file application owner */
  3599. #define H_FDRFLG    73                /* first finder flag */
  3600. #define H_ZERO1        74                /* (should be zero) */
  3601. #define H_WVRT        75                /* folder vertical position */
  3602. #define H_WHRZ        77                /* folder horizontal position */
  3603. #define H_FOLDRID    79                /* folder ID */
  3604. #define H_PROT        81                /* file protected bit (0x01) */
  3605. #define H_ZERO2        82                /* (should be zero) */
  3606. #define H_DLENOFF    83                /* data fork size */
  3607. #define H_RLENOFF    87                /* resource fork size */
  3608. #define H_CTIMOFF    91                /* file creation time */
  3609. #define H_MTIMOFF    95                /* file last time modified time */
  3610. #define H_FDRINFO    99                /* Finder word */
  3611. #define H_FDRFLG2    101                /* second Finder flags */
  3612. #define H_ZERO3        102                /* 15 bytes (should be zero) */
  3613. #define H_UNPKSZ    116                /* hint for unpacking size (unused) */
  3614. #define H_HDR2        120                /* info header size (unused) */
  3615. #define H_UPBIIVER    122                /* highest MacBin II version (unused) */
  3616. #define H_MINBIIVER    123                /* minimum MacBin II version (unused) */
  3617. #define H_CRC        124                /* MacBin II CRC (unused) */
  3618.  
  3619. enum {TEXT, DATA, RSRC, FULL} mode;
  3620.  
  3621. #define LOGLO    (Log > 1)
  3622. #define LOGMED    (Log > 2)
  3623. #define LOGHI    (Log > 3)
  3624.  
  3625. /* C library routines */
  3626. extern char    *getenv();
  3627.  
  3628. struct Macheader
  3629.   { char m_name[NAMEBYTES+1];
  3630.     char m_type[4];
  3631.     char m_author[4];
  3632.     long m_datalen;
  3633.     long m_rsrclen;
  3634.     long m_createtime;
  3635.     long m_modifytime;
  3636.     } Mh;
  3637.  
  3638. struct Filenames
  3639.   { char f_info[256];
  3640.     char f_data[256];
  3641.     char f_rsrc[256];
  3642.     } Files;
  3643. @//E*O*F layers_1.10/macbput.h//
  3644. chmod u=rw,g=r,o=r layers_1.10/macbput.h
  3645.  
  3646. echo x - layers_1.10/makefile
  3647. sed 's/^@//' > "layers_1.10/makefile" <<'@//E*O*F layers_1.10/makefile//'
  3648. #                   Makefile for Layers 1.0
  3649.  
  3650. BIN    = /usr/local
  3651. MANDIR = /usr/local/manl
  3652.  
  3653. PGM    = layers
  3654. PGM2   = layersize
  3655. PGM3   = layertitle
  3656. PGM4   = macbput
  3657. MS     = l
  3658. CFLAGS = -O
  3659. CFILES = layers.c protocol.c
  3660. OFILES = layers.o protocol.o
  3661.  
  3662. default:
  3663.     @echo "Type 'make all' to build all components but not install."
  3664.     @echo "  Read the implications list below for non-setuid installation to"
  3665.     @echo "  guide your decision on whether to setuid the layers command."
  3666.     @echo
  3667.     @echo "Type 'make installsetuid' to install setuid."
  3668.     @echo
  3669.     @echo "Type 'make installnosetuid' to install layers command non-setuid."
  3670.     @echo
  3671.     @echo " Implications of non setuid installation are:"
  3672.     @echo "   1) As with any socket allocating utility your system may be"
  3673.     @echo "      *less* secure with this option if your kernel does not protect"
  3674.     @echo "      virtual tty's from cross user allocation and access. One"
  3675.     @echo "      hole is where the undead program of a disconnected user can be"
  3676.     @echo "      left attached to a socket and a later user allocate the same"
  3677.     @echo "      socket and receive continued output. Another is that any user"
  3678.     @echo "      can read/write to the virtual control terminals of a"
  3679.     @echo "      MacLayers user. (The reason for all this is that the layers"
  3680.     @echo "      utility cannot set the pseudo tty owner to the user.)"
  3681.     @echo "   2) If your utmp file is protected from user writes then"
  3682.     @echo "      users will not be able to do login shell windows (write and"
  3683.     @echo "      talk-like facilities will be unavailable and who-like commands"
  3684.     @echo "      may give inaccurate details.)"
  3685.  
  3686. all: $(PGM) $(PGM2) $(PGM3) $(PGM4)
  3687.  
  3688. $(PGM): $(OFILES)
  3689.     $(CC) $(CFLAGS) -o $(PGM) $(OFILES)
  3690.  
  3691. #    $(CC) $(CFLAGS) -o $(PGM) $(OFILES) -ltermcap
  3692.  
  3693. layers.o: layers.c layers.h
  3694.     $(CC) $(CFLAGS) -c layers.c
  3695.  
  3696. protocol.o: protocol.c layers.h
  3697.     $(CC) $(CFLAGS) -c protocol.c
  3698.  
  3699. $(PGM2): layersize.o
  3700.     $(CC) $(CFLAGS) -o $(PGM2) layersize.o
  3701.  
  3702. $(PGM3): layertitle.o
  3703.     $(CC) $(CFLAGS) -o $(PGM3) layertitle.o
  3704.  
  3705. $(PGM4): macbput.o
  3706.     $(CC) $(CFLAGS) -o $(PGM4) macbput.o
  3707.  
  3708. layersize.o: layersize.c
  3709.     $(CC) $(CFLAGS) -c layersize.c
  3710.  
  3711. layertitle.o: layertitle.c
  3712.     $(CC) $(CFLAGS) -c layertitle.c
  3713.  
  3714. macbput.o: macbput.c macbput.h
  3715.     $(CC) $(CFLAGS) -c macbput.c
  3716.  
  3717. installsetuid: $(PGM) $(PGM2) $(PGM3) $(PGM4)
  3718.     rm -f $(BIN)/$(PGM)
  3719.     install -c -s -o root -g daemon -m 4711 $(PGM) $(BIN)/$(PGM)
  3720.     install -c -s $(PGM2) $(BIN)/$(PGM2)
  3721.     install -c -s $(PGM3) $(BIN)/$(PGM3)
  3722. #    install -c -s $(PGM4) $(BIN)/$(PGM4)
  3723.  
  3724. installnosetuid: $(PGM) $(PGM2) $(PGM3) $(PGM4)
  3725.     rm -f $(BIN)/$(PGM)
  3726.     install -c -s $(PGM) $(BIN)/$(PGM)
  3727.     install -c -s $(PGM2) $(BIN)/$(PGM2)
  3728.     install -c -s $(PGM3) $(BIN)/$(PGM3)
  3729. #    install -c -s $(PGM4) $(BIN)/$(PGM4)
  3730.  
  3731. manpage: layers.1
  3732.     rm -f $(MANDIR)/$(PGM).$(MS)
  3733.     cp layers.1 $(MANDIR)/$(PGM).$(MS)
  3734.     chmod 664 $(MANDIR)/$(PGM).$(MS)
  3735.  
  3736. clean:
  3737.     rm -f a.out core $(PGM) $(PGM2) $(PGM3) $(PGM4) *.o
  3738.  
  3739. shar: makefile 
  3740.     shar -V -c -L60 -o ship README README.V1.10 layers.1 makefile layers.h \
  3741.     layers.c protocol.c layersize.c layertitle.c MacLayers.hqx  \
  3742.     MacLayers.doc macbput.c macbput.h macbput.1
  3743. @//E*O*F layers_1.10/makefile//
  3744. chmod u=rw,g=r,o=r layers_1.10/makefile
  3745.  
  3746. echo x - layers_1.10/protocol.c
  3747. sed 's/^@//' > "layers_1.10/protocol.c" <<'@//E*O*F layers_1.10/protocol.c//'
  3748. /*             Copyright (C) 1989 by David W. Trissel 
  3749.  *
  3750.  *              Not derived from licensed software.
  3751.  *
  3752.  * Permission is granted to freely use, copy, modify, and redistribute
  3753.  * this software, provided that no attempt is made to gain profit from it,
  3754.  * the author is not construed to be liable for any results of using the
  3755.  * software, alterations are clearly marked as such, and this notice is
  3756.  * not modified.
  3757.  *
  3758.  */
  3759.  
  3760. #include    <stdio.h>
  3761. #include    <signal.h>
  3762. #include    <errno.h>
  3763. #include    "layers.h"
  3764.  
  3765.                 /* protocol.c - BSD MacLayers protocol driver */
  3766.  
  3767. /*    This module handles all interaction with the Macintosh MacLayers
  3768. **    program. Services provided are:
  3769. **
  3770. **        InitLink()    - initialize link to MacLayers
  3771. **
  3772. **        TopChannel() - return highest prority channel
  3773. **
  3774. **        SendNew()    - request new layer channel of MacLayers
  3775. **
  3776. **        SendTitle() - change window title to given string (NOT IMPLENTED YET)
  3777. **
  3778. **        SendDelete()- tell MacLayers indicated layer has died
  3779. **
  3780. **        SendQuit()    - order MacLayers to terminate layers mode
  3781. **
  3782. **        SendData()    - send output to indicated channel's window
  3783. **
  3784. **        SendReshape() - send Shape structure to MacLayers
  3785. **
  3786. **        ProcessStreamin() - data is ready to be processed from MacLayers
  3787. **
  3788. */
  3789.  
  3790. #define DUMPALL
  3791. #undef    DUMPALL
  3792.  
  3793. /* C library calls */
  3794. unsigned alarm();                /* alarm system call */
  3795.  
  3796. static int        Start_proto1();
  3797. static int        Start_proto2();
  3798. static int        Start_proto3();
  3799. static int        Start_proto4();
  3800. static int        Start_proto5();
  3801. static int        Start_proto6();
  3802. static int        Start_proto7();
  3803. static int        Start_proto8();
  3804. static int        GetData();
  3805. static void        Packet();
  3806. static void        Parse();
  3807. static void        AwaitInput();
  3808. static void        asciishape();
  3809. static void        fill4();
  3810. static void        fill2();
  3811. static void        fill1();
  3812. static int        parseshape();
  3813. static unsigned    get4();
  3814. static unsigned    get2();
  3815. static unsigned    get1();
  3816. static int        myscanf();
  3817. static int        mygetchar();
  3818. static void        myungetc();
  3819. static int        myalarm();
  3820. static void        dumptime();
  3821.  
  3822. static char        inbuff[IOSIZE];        /* input buffer from MacLayers */
  3823. static char     *inpos;                /* current input position in buffer */
  3824. static int        insize = 0;            /* characters left to process */
  3825. static int        settimeout = 0;        /* alarm system call timeout value */
  3826. static int        Outstream = -1;        /* current output stream channel */
  3827. static int        Instream = -1;        /* current input stream channel */
  3828. static int        Sevenbits = 0;        /* communication channel is 7 bits */
  3829.  
  3830. static struct Shape    SNshape;        /* SendNew() shape response */
  3831. static int        SNresp = 0;            /* SendNew() reponse poll flag */
  3832. static int        SNchan = 0;            /* SendNew() channel return */
  3833. #define SN_WAITING    -1000            /* SendNew() waiting response value */
  3834.  
  3835. #define ATTRSIZE    15                /* size of window attribute string */
  3836.  
  3837. #define FLUSH    fflush(stdout)
  3838.  
  3839.  
  3840.                 /* Initlink() - initialize link with MacLayers */
  3841.  
  3842. /* Returns:
  3843. **                0 - linkup failed
  3844. **                1 - linkup successful, Maclayers now in protocol mode
  3845. */
  3846.  
  3847. int
  3848. Initlink()
  3849. {
  3850.     int Outstream = -1;                /* no default stream yet */
  3851.     int    Instream = -1;                /* no default stream yet */
  3852.     int        num1, num2, num3;        /* scanf item result */
  3853.     int        err;                    /* error code */
  3854.     int        doversion = 0;            /* version swapping flag */
  3855.  
  3856. #define WAITTIME    10                /* second wait response time */
  3857. #define INITTIME    2                /* wait time after succesful startup */
  3858.  
  3859.  
  3860. /*** This patch not yet tested or implemented. Sent to the MacLayers archive 
  3861. **** as:
  3862.  
  3863.  This patch fixes the "Encode request not from host" bug that occurs when
  3864.  running MacLayers 1.00 on a VaxStation 3100 and Ultrix 3.1d.
  3865.  
  3866.  I came across this patch rather accidentally, so take it with a grain of
  3867.  NaCl.
  3868.  
  3869.    ifndef vax
  3870.        /* we must non-buffer input since all input must be immediate 
  3871.        setbuf(stdin, NULL);            /* non-buffer all input 
  3872.    endif
  3873.  
  3874. Archive manager Peter Newton added the following comments:
  3875.  
  3876.       Don't have a VaxStation to try it one.  Many people have had problems 
  3877.       with Ultrix on VaxStations.  We have been giving them uuencoded 
  3878.       binaries made under BSD.
  3879.  
  3880. *****************/
  3881.  
  3882.     /* V1.1 Note: The latest BSD Sun system doesn't break reads from the
  3883.     ** terminal during signals. It appears that System V does do this
  3884.     ** as do earlier BSD systems. At this time no special hacks will
  3885.     ** be installed in just to support Unix versions not doing the breaks.
  3886.     ** Without alarm timeouts host layers will hang if inappropriate
  3887.     ** responses are received during protocol startup. But this should
  3888.     ** only happen when a user types the layers command when not running
  3889.     ** MacLayers.
  3890.     */
  3891.  
  3892.     /* we must non-buffer input since all input must be immediate */
  3893.     setbuf(stdin, NULL);            /* non-buffer all input */
  3894.  
  3895.     /* Host layers after V1.00 can receive protocol level information.
  3896.     ** Send our level as ESC <id>. Version 1.00 MacLayers will treat
  3897.     ** this as an illegal vt-100 sequence and issue a beep. Later versions
  3898.     ** accept our protocol level and return their own after receiving
  3899.     ** our protocol startup sequence sent here.
  3900.     */
  3901.     DO DEBUG("write protocol level 2: ESC 2\n");
  3902.     /* send our protocol level out */
  3903.     if ((err=printf("\033%c", HOSTPROTOCOL + '0')) < 0)
  3904.       { DO DEBUG(" printf() error code %d\n", err);
  3905.         return ( 0 );                /* problem with stdout */
  3906.       }
  3907.     FLUSH;
  3908.  
  3909.     /* send intitial request for terminal type and version number */
  3910.     DO DEBUG("write: ESC [ c\n");
  3911.     printf("\033[c");
  3912.     FLUSH;                            /* force output buffer */
  3913.  
  3914.     /* Attempt to read "ESC [ ? 8 ; typedigits ; versiondigits c" 
  3915.     ** MacLayers in layers mode will return 8 ; 1 c
  3916.     ** MacLayers in startup mode returns    8 ; X c
  3917.     **        were X is the protocol level
  3918.     */
  3919.     num1 = num2 = num3 = -1;        /* default to unsupplied values */
  3920.     DO DEBUG(" doing first scanf\n");
  3921.     (void) myalarm(WAITTIME);        /* set timeout */
  3922.     (void) myscanf("\033[?%d;%d;%dc", &num1, &num2, &num3);
  3923.     (void) myalarm(0);                /* cancel alarm */
  3924.     DO DEBUG("read ESC [ ? %d ; %d; %d c\n", num1, num2, num3);
  3925.     if (num1 != 8 || num2 != 10)
  3926.         return ( 0 );                /* not correct response or layers term ID */
  3927.  
  3928.     DO DEBUG("Client Protocol %d, Host Protocol %d\n", num3, HOSTPROTOCOL);
  3929.  
  3930.     /* Terminal type was valid, now verify protocol number */
  3931.     switch (num3)
  3932.     { case 1:
  3933.       case 2:
  3934.       case 3:
  3935.       case 4:
  3936.       case 5:
  3937.       case 6:
  3938.         /* these are all valid levels */
  3939.         break;                        /* break for valid levels */
  3940.  
  3941.       case 9:
  3942.         num3 = 7;                    /* 9 represents level 7 */
  3943.         break;
  3944.  
  3945.       case 0:
  3946.         num3 = 8;                    /* 0 represents level 8 */
  3947.         break;
  3948.  
  3949.       default:
  3950.         /* invalid response */
  3951.         return ( 0 );                /* incorrect protocol level */
  3952.  
  3953.     } /* client protocol level switch */
  3954.  
  3955.     Clientlevel = num3;                /* set client protocol level offered */
  3956.  
  3957.     /* final protocol level cannot be higher than our current support level */
  3958.     if (num3 > HOSTPROTOCOL)
  3959.       {    DO DEBUG("Protocol level forced down to host level\n");
  3960.         num3 = HOSTPROTOCOL;        /* force back down to the host level */
  3961.       }
  3962.  
  3963.     Protocollevel = num3;            /* set effective protocol level */
  3964.  
  3965.     /* execute proper startup protocol level routine */
  3966.     switch (Protocollevel)
  3967.     { case 1:
  3968.         return ( Start_proto1() );    /* handle protocol 1 startup sequence */
  3969.  
  3970.       case 2:
  3971.         return ( Start_proto2() );    /* handle protocol 2 startup sequence */
  3972.  
  3973.       case 3:
  3974.         return ( Start_proto3() );    /* handle protocol 3 startup sequence */
  3975.  
  3976.       case 4:
  3977.         return ( Start_proto4() );    /* handle protocol 4 startup sequence */
  3978.  
  3979.       case 5:
  3980.         return ( Start_proto5() );    /* handle protocol 5 startup sequence */
  3981.  
  3982.       case 6:
  3983.         return ( Start_proto6() );    /* handle protocol 6 startup sequence */
  3984.  
  3985.       case 7:
  3986.         return ( Start_proto7() );    /* handle protocol 7 startup sequence */
  3987.  
  3988.       case 8:
  3989.         return ( Start_proto8() );    /* handle protocol 8 startup sequence */
  3990.  
  3991.     }
  3992.  
  3993.     /* invalid - refuse startup */
  3994.     return ( 0 );                    /* SHOULD NOT OCCUR */
  3995.  
  3996. } /* Initlink() */
  3997.  
  3998.  
  3999.                     /* Start_proto1() - Protocol 1 startup sequence */
  4000.  
  4001. static int
  4002. Start_proto1()
  4003. {
  4004.     int        num1;                    /* scanf item result */
  4005.  
  4006.     /* This is the original MacLayers protocol for V1.00 */
  4007.  
  4008.     /* ask terminal if ENC_ENABLE is to be forced */
  4009.     DO DEBUG("write: ESC [ F\n");
  4010.     (void) printf("\033[F");
  4011.     FLUSH;                            /* force output buffer */
  4012.  
  4013.     /* attempt to read "ESC [ flag F" (flag indicates ENC_ENABLE status) */
  4014.     num1 = -1;                        /* default to invalid response */
  4015.     (void) myalarm(WAITTIME);        /* set timeout */
  4016.     (void) myscanf("\033[%dF", &num1);
  4017.     (void) myalarm(0);                /* cancel alarm */
  4018.     DO DEBUG("read ESC [ %d F\n", num1);
  4019.     if (num1 != 1 && num1 != 0)
  4020.         return ( 0 );                /* something's wrong */
  4021.     if (num1 == 1)
  4022.         Sevenbits = 1;                /* we are processing 7-bit data */
  4023.  
  4024.     /* now startup packet mode in non ENC_ENABLE processing */
  4025.     DO DEBUG("write: ESC [ 2 ; 0 v\n");
  4026.     (void) printf("\033[2;0v");        /* "ESC [ 2 ; 0 v" */
  4027.     FLUSH;                            /* force output buffer */
  4028.  
  4029. #if 0
  4030.     {    int    i,j;
  4031.         for (i=0; i<20; i++)
  4032.         {    j = mygetchar();
  4033.             DO DEBUG("fuck read 0x%lx == %c\n", j, j);
  4034.         }
  4035.         return (0 );
  4036.     }
  4037. #endif
  4038. #if 0
  4039.         /* We must reset buffer to reread this character. Note
  4040.         ** this won't work for triggering reads by layers.c unless 
  4041.         ** client is sending more than 1 character because the select()
  4042.         ** system call is used.
  4043.         */
  4044.         /* ungetc(num1, stdin);        /* return character back for re-read */
  4045.         myungetc(num1);                /* re-insert this character */
  4046. #endif
  4047. #if 0
  4048.         insize = 1;                    /* preset buffer with one character */
  4049.         inpos = inbuff;                /* setup buffer pointer */
  4050.         inbuff[0] = num1;            /* setup to reread this character */
  4051. #endif
  4052.     Clientlevel = 1;             /* assume protocol is level 1 */
  4053.  
  4054.     /* we are now in packet mode */
  4055.     sleep( INITTIME );                /* let Macintosh keep up with us */
  4056.  
  4057.     return ( 1 );                    /* return successful startup */
  4058.  
  4059. } /* Start_proto1() */
  4060.  
  4061.  
  4062.                 /* Start_proto2() - Protocol 2 startup sequence */
  4063.  
  4064. static int
  4065. Start_proto2()
  4066. {
  4067.     /* This is the second MacLayers protocol starting with V1.1 */
  4068.  
  4069.     /* we are now in packet mode */
  4070.     sleep( INITTIME );                /* let Macintosh keep up with us */
  4071.  
  4072.     return ( 1 );                    /* return successful startup */
  4073.  
  4074. } /* Start_proto2() */
  4075.  
  4076.  
  4077.  
  4078.                 /* Start_proto3() - Protocol 3 startup sequence */
  4079.  
  4080. static int
  4081. Start_proto3()
  4082. {
  4083.     /* not yet defined! */
  4084.     return ( 0 );                    /* SHOULD NOT OCCUR */
  4085.  
  4086. } /* Start_proto3() */
  4087.  
  4088.  
  4089.  
  4090.                 /* Start_proto4() - Protocol 4 startup sequence */
  4091.  
  4092. static int
  4093. Start_proto4()
  4094. {
  4095.     /* not yet defined! */
  4096.     return ( 0 );                    /* SHOULD NOT OCCUR */
  4097.  
  4098. } /* Start_proto4() */
  4099.  
  4100.  
  4101.  
  4102.                 /* Start_proto5() - Protocol 5 startup sequence */
  4103.  
  4104. static int
  4105. Start_proto5()
  4106. {
  4107.     /* not yet defined! */
  4108.     return ( 0 );                    /* SHOULD NOT OCCUR */
  4109.  
  4110. } /* Start_proto5() */
  4111.  
  4112.  
  4113.  
  4114.                 /* Start_proto6() - Protocol 6 startup sequence */
  4115.  
  4116. static int
  4117. Start_proto6()
  4118. {
  4119.     /* not yet defined! */
  4120.     return ( 0 );                    /* SHOULD NOT OCCUR */
  4121.  
  4122. } /* Start_proto6() */
  4123.  
  4124.  
  4125.  
  4126.                 /* Start_proto7() - Protocol 7 startup sequence */
  4127.  
  4128. static int
  4129. Start_proto7()
  4130. {
  4131.     /* not yet defined! */
  4132.     return ( 0 );                    /* SHOULD NOT OCCUR */
  4133.  
  4134. } /* Start_proto7() */
  4135.  
  4136.  
  4137.  
  4138.                 /* Start_proto8() - Protocol 8 startup sequence */
  4139.  
  4140. static int
  4141. Start_proto8()
  4142. {
  4143.     /* not yet defined! */
  4144.     return ( 0 );                    /* SHOULD NOT OCCUR */
  4145.  
  4146. } /* Start_proto8() */
  4147.  
  4148.  
  4149.             /* TopChannel() - return highest prority channel */
  4150.  
  4151. int
  4152. TopChannel()
  4153. {
  4154.     return ( Instream );
  4155.  
  4156. } /* TopChannel() */
  4157.  
  4158.  
  4159.     /*
  4160.     ** WARNING: Most of the following functions may be recursively called
  4161.     **            as control commands are processed from the input stream
  4162.     */
  4163.  
  4164.  
  4165.             /* ProcessStreamin() - MacLayers has input to process */
  4166.  
  4167. void
  4168. ProcessStreamin()
  4169. {
  4170.     int        c;                        /* input character being processed */
  4171.  
  4172.     DO dumptime();
  4173.     DO DEBUG("ProcessStreamin() insize %d\n", insize);
  4174.  
  4175.     GetData();                        /* read some */
  4176.  
  4177.     while (insize > 0)                /* while more data to process ... */
  4178.         Parse();                    /* process next chuck of data */
  4179.  
  4180. } /* ProcessStreamin() */
  4181.  
  4182.  
  4183.         /* SendNew() - request new layer channel from MacLayers */
  4184.  
  4185. /*    This command is unique in that it returns a response from MacLayers.
  4186. **    To do this we continue processing the input stream until we get
  4187. **    our return. (This leads to recursive conditions.) The variables
  4188. **    'SNresp', 'SNshape' and 'SNchan' are set when our reply is received.
  4189. */
  4190. int
  4191. SendNew(shape)
  4192. struct Shape    *shape;                /* shape to use for new window */
  4193. {
  4194.     int            i;                    /* attribute count variable */
  4195.     char        astring[ATTRSIZE];    /* copy of attribute string */
  4196.  
  4197.     DO dumptime();
  4198.     DO DEBUG("SendNew() new layer requested: '~%cA'\n", '1'+ATTRSIZE);
  4199.  
  4200.     /* check for a recursive call */
  4201.     if (SNresp == SN_WAITING)
  4202.       {    DO DEBUG("return 0 - recursive call\n");
  4203.         return ( 0 );                /* return failure */
  4204.       }
  4205.  
  4206.     putchar(ESCAPE);                /* send start of control packet char */
  4207.     putchar('1' + ATTRSIZE);        /* send command size */
  4208.     putchar('A');                    /* send command */
  4209.     asciishape(shape, astring);        /* convert shape to string */
  4210.     for (i=0; i < ATTRSIZE; i++)
  4211.         putchar(astring[i]);        /* send next attribute digit */
  4212.     FLUSH;
  4213.  
  4214.     /* now stay here and process the input stream until we see our response */
  4215. /**** THIS SHOULD BE ENHANCED TO TIMEOUT WITH GetData() AND REISSUE REQUEST */
  4216.     SNresp = SN_WAITING;            /* indicate we are waiting a response */
  4217.     while (SNresp == SN_WAITING)
  4218.       { DO DEBUG(" while (SNresp %d == %d)\n", SNresp, SN_WAITING);
  4219.         AwaitInput();                /* wait till input from MacLayers arrives */
  4220.         ProcessStreamin();            /* process available input */
  4221.       }
  4222.  
  4223.     if (SNresp == -1)                /* if Maclayers rejected request */
  4224.         SNchan = 0;                    /* return failure channel of zero */
  4225.     else
  4226.         *shape = SNshape;            /* else update shape structure */
  4227.  
  4228.     DO DEBUG("SendNew() returning channel %d\n", SNchan);
  4229.  
  4230.     return ( SNchan );                /* return the indicated channel */
  4231.  
  4232. } /* SendNew() */
  4233.  
  4234.  
  4235.             /* SendReshape() - send to shape to MacLayers */
  4236.  
  4237. void
  4238. SendReshape(chan, shape)
  4239. int                chan;                /* channel shape belongs to */
  4240. struct Shape    *shape;                /* shape to use for new window */
  4241. {
  4242.     int            i;                    /* attribute count variable */
  4243.     char        astring[ATTRSIZE];    /* copy of attribute string */
  4244.  
  4245.     DO dumptime();
  4246.     DO DEBUG("SendReshape() reshape: '~%cA'\n", '2'+ATTRSIZE);
  4247.  
  4248.     if (chan <= 0 || chan > MAXPCHAN)
  4249.       {    DO DEBUG("BAD CHANNEL!!!\n");
  4250.         return;                        /* ignore request */
  4251.       }
  4252.  
  4253.     putchar(ESCAPE);                /* send start of control packet char */
  4254.     putchar('2' + ATTRSIZE);        /* send command size */
  4255.     putchar('R');                    /* send command */
  4256.     putchar(chan + '0');            /* send channel */
  4257.     asciishape(shape, astring);        /* convert shape to string */
  4258.     DO DEBUG("shape: %.*s\n", ATTRSIZE, astring);
  4259.     for (i=0; i < ATTRSIZE; i++)
  4260.         putchar(astring[i]);        /* send next attribute digit */
  4261.     FLUSH;
  4262.  
  4263. } /* SendReshape() */
  4264.  
  4265.  
  4266.             /* SendTitle() - set layer's window title */
  4267.  
  4268. void
  4269. SendTitle(chan, buff, cnt)
  4270. int            chan;                    /* layer window ID */
  4271. char        *buff;                    /* new title string */
  4272. int            cnt;                    /* count of title length */
  4273. {
  4274.     int        i;                        /* work variable */
  4275.  
  4276.     DO DEBUG("SendTitle(chan%d, len %d, '%.*s')\n", chan, cnt, cnt, buff);
  4277.  
  4278.     if (chan <= 0 || chan > MAXPCHAN)
  4279.       {    DO DEBUG("BAD CHANNEL!!!\n");
  4280.         return;                        /* ignore request */
  4281.       }
  4282.  
  4283.     if (cnt < 0)
  4284.       {    DO DEBUG("BAD COUNT!!!\n");
  4285.         return;                        /* ignore request */
  4286.       }
  4287.  
  4288.     /* for now chop title size to 29 chars since that's MacLayer's limit */
  4289.     if (cnt > 29)
  4290.         cnt = 29;                    /* due to packet size limit */
  4291.  
  4292.     /* we must guarantee that the size will not appear to be another ESCAPE */
  4293.     if ('2' + cnt == ESCAPE)
  4294.         cnt--;                        /* truncate to avoid ESCAPE ESCAPE */
  4295.     
  4296.     putchar(ESCAPE);                /* send start of control packet char */
  4297.     putchar('2' + cnt);                /* send size of packet */
  4298.     putchar('T');                    /* send command */
  4299.     putchar(chan + '0');            /* send channel ID */
  4300.     for (i=0; i<cnt; i++)
  4301.         putchar(buff[i]);            /* send out title */
  4302.     FLUSH;
  4303.  
  4304. } /* SendTitle() */
  4305.  
  4306.  
  4307.             /* SendDelete() - tell Maclayers layer died */
  4308.  
  4309. void
  4310. SendDelete(chan)
  4311. int        chan;                        /* dead channel ID */
  4312. {
  4313.     DO DEBUG("SendDelete(%d) '~2D%d'\n", chan, chan);
  4314.  
  4315.     if (chan <= 0 || chan > MAXPCHAN) /* check channel ID */
  4316.       {    DO DEBUG("BAD CHANNEL!!!\n");
  4317.         return;                        /* ignore request */
  4318.       }
  4319.  
  4320.     putchar(ESCAPE);                /* send control packet start char */
  4321.     putchar('2');                    /* send command size */
  4322.     putchar('D');                    /* send command character */
  4323.     putchar(chan + '0');            /* channel ID in ascii */
  4324.     FLUSH;
  4325.  
  4326. } /* SendDelete() */
  4327.  
  4328.  
  4329.             /* SendQuit() - order MacLayers to end layers mode */
  4330.  
  4331. void
  4332. SendQuit(chan)
  4333. int        chan;                        /* dead channel ID */
  4334. {
  4335.     DO dumptime();
  4336.     DO DEBUG("SendQuit() '~1E'\n");
  4337.  
  4338.     putchar(ESCAPE);                /* send control packet start char */
  4339.     putchar('1');                    /* send command size */
  4340.     putchar('E');                    /* send command */
  4341.     FLUSH;
  4342.  
  4343. } /* SendQuit() */
  4344.  
  4345.  
  4346.             /* SendData() - send output to layer's window */
  4347.  
  4348. void
  4349. SendData(chan, buff, cnt)
  4350. int            chan;                    /* layer window ID */
  4351. unsigned char *buff;                /* new title string */
  4352. int            cnt;                    /* count of title length */
  4353. {
  4354.     unsigned c;                        /* output character being sent */
  4355.  
  4356.     DO
  4357.       {    int        dcnt;
  4358.  
  4359.         dumptime();
  4360.         DEBUG("SendData(chan %d, len %d, '", chan, cnt, cnt, buff);
  4361.         for (dcnt=0; dcnt<cnt; dcnt++)
  4362.             DEBUG("%c", buff[dcnt]); /* dump each char so null doesn't stop */
  4363.         DEBUG("')\n");
  4364.       }
  4365.  
  4366.     if (chan <= 0 || chan > MAXPCHAN)
  4367.       {    DO DEBUG("BAD CHANNEL!!!\n");
  4368.         return;                        /* ignore request */
  4369.       }
  4370.  
  4371.     /* if new output channel stream then prefix redirect command */
  4372.     if (chan != Outstream)
  4373.       {    DO DEBUG("Redirecting output to %d '~2O%d'\n", chan, chan);
  4374.         putchar(ESCAPE);            /* start of command sequence */
  4375.         putchar('2');                /* send command size */
  4376.         putchar('O');                /* send command */
  4377.         putchar(chan + '0');        /* put out channel in ASCII */
  4378.         Outstream = chan;            /* new output stream set */
  4379.       }
  4380.  
  4381.     /* transmit the buffer converting the ESCAPE sequence to double ESCAPE */
  4382.     while (cnt--)
  4383.       {    c = *buff++;                /* get next output character */
  4384. #ifdef DUMPALL
  4385.         DO DEBUG("outchar %c 0x%x\n", c, c);
  4386. #endif
  4387.         if (c == ESCAPE || c == (ESCAPE + 0x80))
  4388.           {    putchar(c);                /* put it out twice */
  4389. #ifdef DUMPALL
  4390.             DO DEBUG(" Doubled Escape!\n");
  4391. #endif
  4392.           }
  4393.         putchar(c);                    /* write character out */
  4394.       }
  4395.  
  4396.     FLUSH;                            /* force out queued output characters */
  4397.         
  4398. } /* SendData() */
  4399.  
  4400.  
  4401.             /* Parse() - process next chunk of input stream */
  4402.  
  4403. static void
  4404. Parse()
  4405. {
  4406. #define    ST_NULL        0                /* not primed for next state yet */
  4407. #define    ST_STREAM    1                /* processing default stream input */
  4408. #define    ST_PKT        2                /* processing packet data */
  4409.  
  4410.     int        c;                        /* input character being processed */
  4411.  
  4412.     static    int state = ST_NULL;    /* current input state */
  4413.     static    int psize = 0;            /* packet size */
  4414.     static    int    rempsize = 0;        /* remembered packet size */
  4415.     static    char pdata[MAXSTR];        /* area for packet data */
  4416.     static    char *ppos;                /* packet read insert position */
  4417.     static    int escapemode = 0;        /* processing escape character */
  4418.     static    int    escapechar;            /* escape character being processed */
  4419.     static    pchan = -1;                /* packet input stream channel */
  4420.  
  4421.     DO dumptime();
  4422.     DO DEBUG("Parse() insize %d\n", insize);
  4423.  
  4424.     while (insize-- > 0)            /* while more data */
  4425.       {    c = *inpos++;                /* get next character */
  4426.         switch (state)                /* process according to state */
  4427.         { case ST_NULL:                /* prepare for new packet */
  4428.             DO DEBUG("ST_NULL\n");
  4429.             psize = 0;                /* clear packet size */
  4430.             ppos = pdata;            /* start fill at data position */
  4431.             pchan = Instream;        /* packet channel is current input stream */
  4432.             state = ST_STREAM;        /* default is stream processing */
  4433.  
  4434.           case ST_STREAM:
  4435.             /* stream keyboard input for layer */
  4436.             /* check for escape char with possible high bit on */
  4437. #ifdef DUMPALL
  4438.             DO DEBUG("ST_STREAM %x/%x '%c' esc %d insz %d\n",
  4439.                         c, c & 0x7f, c & 0x7f, escapemode, insize);
  4440. #endif
  4441.             if (c == ESCAPE || c == (ESCAPE | 0x80))
  4442.               {    if (escapemode && c == escapechar) /* previous was ESCAPE */
  4443.                 /* this is really a single ESCAPE character */
  4444.                     escapemode = 0;        /* back out of ESCAPE mode */
  4445.                 else
  4446.                     /* what do we do with back to back esc esc+0x80 ? */
  4447.                   {    /* flag in escape mode */
  4448.                     escapemode++;
  4449.                     escapechar = c;        /* remember character used for escape */
  4450.                     continue;            /* and continue scan */
  4451.                   }
  4452.               }
  4453.             else
  4454.             if (escapemode)
  4455.               { /* this is the start of a control packet */
  4456.                 if (psize)                /* if we have previous data packet */
  4457.                     Packet(pchan, psize, pdata); /* finish up previous pkt */
  4458.                 /* process packet size */
  4459.                 psize = (c & 0x7f) - '0'; /* save size byte */
  4460.                 if (psize <= 0 || psize > MAXSTR)
  4461.                   {    /* bad size */
  4462.                     DO DEBUG("Bad pkt size %d\n", psize);
  4463.                     break;                /* trash this packet */
  4464.                   }
  4465.                 rempsize = psize;        /* remember this size for later */
  4466. #if 0
  4467.                 ptimo = rtimo;            /* start receive timeout */                
  4468. #endif
  4469.                 escapemode = 0;            /* escape mode now off */
  4470.                 ppos = pdata;            /* initialize data store pointer */
  4471.                 state = ST_PKT;            /* expect packet data next */
  4472.                 continue;                /* continue scan */
  4473.               }
  4474.                   
  4475.             /* process standard data output character for current stream */
  4476.             
  4477.             *ppos++ = c;                /* save next data character */
  4478.                 
  4479.             if (++psize >= MAXSTR)        /* if packet full ... */
  4480.               {    Packet(pchan, psize, pdata); /* process this packet */
  4481.                 break;                    /* end packet processing */
  4482.               }                  
  4483.             continue;                    /* continue scan */
  4484.                                                 
  4485.           case ST_PKT:
  4486.             /* process next paket data byte */
  4487.             *ppos++ = c & 0x7f;        /* store next data byte */
  4488. #ifdef DUMPALL
  4489.             DO DEBUG("ST_PKT: %x '%c' sz %d\n", c & 0x7f, c & 0x7f, psize);
  4490. #endif
  4491.             if (--psize != 0)
  4492.                 continue;
  4493. #if 0
  4494.             if (crc((unsigned char *) &rpkt, rpkt.pkt.HEADER_DSIZE+2))
  4495.                 STATS(Scrcerr);            /* communications error */
  4496.             else
  4497. #endif
  4498.             Packet(0, rempsize, pdata); /* process it */
  4499.                 
  4500.             } /* end build packet switch */
  4501.             
  4502. #if 0
  4503.         ptimo = 0;                        /* no more receive timeout */
  4504. #endif
  4505.         state = ST_NULL;                /* no more receive packet in progress */
  4506.             
  4507.       } /* end while (insize) */
  4508.           
  4509.     if (state == ST_STREAM && psize )    /* if we have some data ... */
  4510.       {    Packet(Instream, psize, pdata); /* process this data */
  4511. #if 0
  4512.         ptimo = 0;                        /* no more receive timeout */
  4513. #endif
  4514.         state = ST_NULL;                /* no more receive packet in progress */
  4515.       }
  4516.  
  4517. } /* Parse() */
  4518.  
  4519.  
  4520.         /* Packet() - prcess next input data string or control packet */
  4521. static void
  4522. Packet(chan, size, buff)
  4523. int            chan;                        /* channel (0 if control packet) */
  4524. int            size;                        /* amount of data */
  4525. char        *buff;                        /* pointer to packet data */
  4526. {
  4527.     static struct Shape shape;            /* Shape structure */
  4528.  
  4529.     DO dumptime();
  4530.     DO DEBUG("Packet(chan %d, size %d, '%.*s')\n", chan, size, size, buff);
  4531.  
  4532.     /* verify channel */
  4533.     if (chan < 0 || chan > MAXPCHAN)
  4534.       {    DO DEBUG("BAD CHANNEL!!\n");
  4535.         return;                            /* ignore bad channel */
  4536.       }
  4537.  
  4538.     /* if data packet (chan>0) feed data to server */
  4539.     if (chan > 0)
  4540.       {    ReceiveData(chan, buff, size);
  4541.         return;                            /* we are through */
  4542.       }
  4543.  
  4544.     /* control packet (channel 0) */
  4545.     chan = buff[1] - '0';                /* assume channel specified */
  4546.     if (chan < 0 || chan > MAXPCHAN)    /* if invalid ... */
  4547.         chan = 0;                        /* set to zero */
  4548.  
  4549.     switch (buff[0])
  4550.     { case 'I':        /* redirect stream */
  4551.         DO DEBUG("CMD 'I' redirect stream to %c\n", buff[1]);
  4552.         if (size != 2)                    /* verify size */
  4553.             break;                        /* break if bad */
  4554.         if (chan == 0)                    /* verify channel */
  4555.             break;                        /* break if bad */
  4556.         Instream = chan;                /* new instream channel */
  4557.         return;                            /* we are through */
  4558.  
  4559.       case 'A':        /* returned A_NEWLAYER packet */
  4560.         DO DEBUG("CMD 'A' A_NEWLAYER response %c newchan %c SNresp %d\n",
  4561.                     buff[2], buff[1], SNresp);
  4562.         if (size != 3 + ATTRSIZE)
  4563.             break;                        /* break if bad */
  4564.  
  4565.         /* if SendNew() not waiting for a response this is invalid */
  4566.         if (SNresp != SN_WAITING)
  4567.             break;                        /* break if bad */
  4568.  
  4569.         if (buff[2] == '1')                /* if response is "failed" ... */
  4570.             SNresp = -1;                /* show -1 response */
  4571.         else
  4572.         if (buff[2] == '0')                /* if response is "success" ... */
  4573.           {    if (chan == 0)                /* if invalid channel */
  4574.                 break;                    /* break if bad */
  4575.             /* build shape structure for SendNew() */
  4576.             if (parseshape(&SNshape, &buff[3]) == -1)
  4577.                 break;                    /* if invalid data then bad packet */
  4578.             SNresp = 0;                    /* show good response */
  4579.             SNchan = chan;                /* indicate channel returned */
  4580.           }
  4581.         else
  4582.             break;                        /* break if bad */
  4583.  
  4584.         DO DEBUG("SNresp = %d, SNchan = %d\n", SNresp, SNchan);
  4585.         return;                            /* we are through */
  4586.         
  4587.       case 'N':        /* new layer creation */
  4588.         DO DEBUG("CMD 'N' new layer creation newchan %c\n", buff[1]);
  4589.         if (size != 2 + ATTRSIZE)        /* verify size */
  4590.             break;                        /* break if bad */
  4591.         if (chan == 0)                    /* verify channel */
  4592.             break;                        /* break if bad */
  4593.         /* build shape structure */
  4594.         if (parseshape(&shape, &buff[2]) == -1)
  4595.             break;                        /* if invalid data then bad packet */
  4596.         ReceiveNew(chan, &shape);        /* pass to server */
  4597.         return;                            /* packet is done */
  4598.  
  4599.       case 'D':        /* deleted layer */
  4600.         DO DEBUG("CMD 'D' deleted layer %c\n", buff[1]);
  4601.         if (size != 2)                    /* verify size */
  4602.             break;                        /* break if bad */
  4603.         if (chan == 0)                    /* verify channel */
  4604.             break;                        /* break if bad */
  4605.         ReceiveDelete(chan);            /* pass on to server */
  4606.         return;                            /* packet is done */
  4607.  
  4608.       case 'E':        /* exit - awaiting shutdown */
  4609.         DO DEBUG("CMD 'E' exit MacLayers awaiting shutdown msg\n");
  4610.         if (size != 1)                    /* verify size */
  4611.             break;                        /* break if bad */
  4612.         ReceiveQuit();                    /* pass to server */
  4613.         /* NOT REACHED*/
  4614.         return;                            /* ?? should never reach here */
  4615.  
  4616.       case 'R':        /* reshaped */
  4617.         DO DEBUG("CMD 'R' reshape chan %c\n", buff[1]);
  4618.  
  4619.         if (size != 2 + ATTRSIZE)        /* verify size */
  4620.             break;                        /* break if bad */
  4621.  
  4622.         if (chan == 0)                    /* verify channel */
  4623.             break;                        /* break if bad */
  4624.  
  4625.         /* build shape structure */
  4626.         if (parseshape(&shape, &buff[2]) == -1)
  4627.             break;                        /* if invalid data then bad packet */
  4628.  
  4629.         ReceiveReshape(chan, &shape);     /* tell server about shape */
  4630.         return;                            /* packet processed */
  4631.  
  4632.       case 'S':        /* signal */
  4633.         DO DEBUG("CMD 'S' SIGNAL chan %c sig %c\n", buff[1], buff[2]);
  4634.         if (size != 3)                    /* verify size */
  4635.             break;                        /* break if bad */
  4636.         if (chan == 0)
  4637.             break;                        /* break if bad */
  4638.  
  4639.         if (buff[2] == '0')                /* if SIGINT */
  4640.             size = SIGINT;                /* yes */
  4641.         else
  4642.         if (buff[2] == '1')                /* if SIGHUP */
  4643.             size = SIGHUP;                /* yes */
  4644.         else
  4645.             break;                        /* invalid signal */
  4646.             
  4647.         ReceiveSignal(chan, size);        /* pass to server */
  4648.         return;                            /* packet processed */
  4649.  
  4650.       default:
  4651.         DO DEBUG("ILLEGAL CONTROL PACKET!!!\n");
  4652.         return;                            /* ignore bad packet */
  4653.  
  4654.     } /* end command packet switch */
  4655.  
  4656.     /* switch falls out if bad size or channel for given command */
  4657.     DO DEBUG("Invalid size or channel!!!\n");    /* dump error */
  4658.     return;                                /* ignore packet */
  4659.  
  4660. } /* Packet() */
  4661.  
  4662.  
  4663.             /* GetData() - read next input from MacLayers stream */
  4664.  
  4665. /*    The settimeout variable indicates if we return when nothing
  4666. **    is read within a certain amount of seconds. The return code is:
  4667. **
  4668. **        0 - timeout occured and no data was read
  4669. **
  4670. **        1 - no timeout occured, data read
  4671. */
  4672. static int
  4673. GetData()
  4674. {
  4675.     int        result;                    /* return from read() */
  4676.     int        i;                        /* work counter */
  4677.     char    *ptr;                    /* work pointer */
  4678.  
  4679.     DO dumptime();
  4680.     DO DEBUG("GetData()\n");
  4681.  
  4682.     /* if buffer still has data simply return (SHOULD NOT OCCUR?) */
  4683.     if (insize > 0)
  4684.       {    DO DEBUG("early return insize %d\n", insize);
  4685.         return ( 1 );                /* act as through data read */
  4686.       }
  4687.     inpos = inbuff;                    /* next get will start at beginning */
  4688.     insize = 0;                        /* default insize back to zero */
  4689.  
  4690.     /* set timeout if we are to do so */
  4691.     if (settimeout)
  4692.       {    DO DEBUG("alarm(%d)\n", settimeout);
  4693.         (void) alarm(settimeout);    /* set timeout in seconds */
  4694.       }
  4695.  
  4696.     /* do the read from stdin */
  4697.     result = read(0, inbuff, IOSIZE);
  4698.  
  4699.     /* if alarm was set cancel it now */
  4700.     if (settimeout)
  4701.       {    DO DEBUG("alarm(0)\n");
  4702.         (void) myalarm(0);            /* cancel alarm */
  4703.       }
  4704.  
  4705.     /* check for timeout or error */
  4706.     /* EWOULDBLOCK for no data avail -(but we should not see this) */
  4707.     /* EINTR if signal stopped the read -(rare but could happen) */
  4708.     if (result <= 0)
  4709.       {    DO DEBUG(" ?? no data result %d\n", result);
  4710.         return ( 0 );                /* return nothing read */
  4711.       }
  4712.  
  4713.     /* return with fresh buffer data */
  4714.     insize = result;
  4715.  
  4716.     /* if 7-bit communication channel then strip all high bits */
  4717.     if (Sevenbits)
  4718.       for (i=result,ptr = inbuff; i>0; --i)
  4719.         *ptr++ &= 0x7f;                /* strip high bit */
  4720.  
  4721.     DO DEBUG("read %d bytes\n", insize);
  4722.     return ( 1 );                    /* return OK code */
  4723.  
  4724. } /* GetData() */
  4725.  
  4726.  
  4727.             /* AwaitInput() - wait for more input from MacLayers */
  4728.  
  4729. static void
  4730. AwaitInput()
  4731. {
  4732.     int        r;                        /*  read descriptor bits */
  4733.  
  4734.     DO dumptime();
  4735.     DO DEBUG("AwaitInput() insize %d\n", insize);
  4736.  
  4737.     /* if buffer has data then don't wait */
  4738.     if (insize > 0)
  4739.       {    DO DEBUG("Return early insize %d\n", insize);
  4740.         return;
  4741.       }
  4742.  
  4743.     do
  4744.       {    r = 1<<0;                    /* wait for read from input device */
  4745.         if (select(32, &r, NULL, NULL, NULL) == -1)    /* if problem waiting ... */
  4746.           {    if (errno != EINTR)            /* if not simply signal taken ... */
  4747.               {    /* SHOULD NOT OCCUR - shutdown layers */
  4748.                 DO DEBUG("AwaitInput: select error %d\n", errno);
  4749.                 printf("layers: AwaitInput: bad select %d\n", errno);
  4750.                 FQuit();                    /* shutdown layers */
  4751.                 /* NOT REACHED */
  4752.               }
  4753.           }
  4754.       } while ((r & 1<<0) == 0);
  4755.         
  4756. } /* AwaitInput() */
  4757.  
  4758.                 /* asciishape() - convert Shape structure to ASCII */
  4759. static void
  4760. asciishape(shape, loc)
  4761. struct Shape    *shape;                        /* Shape structure for channel */
  4762. char            *loc;                        /* location to start filling result */
  4763. {
  4764.     char        *origloc;                    /* (for debuggin) */
  4765.  
  4766.     origloc = loc;                            /* remember start of string */
  4767.     fill4(&loc, shape->worigh);                /* origin h */
  4768.     fill4(&loc, shape->worigv);                /* origin v */
  4769.     fill2(&loc, shape->wlines);                /* lines high */
  4770.     fill2(&loc, shape->wchars);                /* chars wide */
  4771.     fill1(&loc, shape->wfont);                /* font size */
  4772.     fill2(&loc, shape->wattr);                /* attributes */
  4773.  
  4774.     DO DEBUG("asciishape(): %.*s\n", ATTRSIZE, origloc);
  4775.  
  4776. } /* asciishape() */
  4777.  
  4778.  
  4779.                     /* fill4() - convert parameter to ASCII */
  4780.  
  4781. static void
  4782. fill4(loc, valu)
  4783. char        **loc;                            /* pointer to fill area pointer */
  4784. unsigned    valu;                            /* value to use */
  4785. {
  4786.     fill2(loc, valu>>8);                    /* fill high half word */
  4787.     fill2(loc, valu & 0xff);                /* fill low half word */
  4788.  
  4789. } /* fill4() */
  4790.  
  4791.  
  4792.                     /* fill2() - convert parameter to ASCII */
  4793.  
  4794. static void
  4795. fill2(loc, valu)
  4796. char        **loc;                            /* pointer to fill area pointer */
  4797. unsigned    valu;                            /* value to use */
  4798. {
  4799.     fill1(loc, valu>>4);                    /* fill high byte */
  4800.     fill1(loc, valu & 0xf);                    /* fill low byte */
  4801.     
  4802. } /* fill2() */
  4803.  
  4804.  
  4805.                     /* fill1() - convert parameter to ASCII */
  4806.  
  4807. static void
  4808. fill1(loc, valu)
  4809. char        **loc;                            /* pointer to fill area pointer */
  4810. unsigned    valu;                            /* value to use */
  4811. {
  4812.     *(*loc)++ = "0123456789ABCDEF"[valu & 0xf]; /* return hex value */
  4813.  
  4814. } /* fill1() */
  4815.  
  4816.  
  4817.             /* parseshape() - convert ASCII image to Shape structure */
  4818.                 
  4819. static int    Badconvert;                        /* indicates bad conversion */
  4820.  
  4821. static int
  4822. parseshape(shape, loc)
  4823. struct Shape    *shape;                        /* Shape structure for channel */
  4824. char            *loc;                        /* location to start parsing */
  4825. {
  4826.     Badconvert = 0;                            /* clear bad characters indicator */
  4827.     shape->worigh = get4(&loc);                /* origin h */
  4828.     shape->worigv = get4(&loc);                /* origin v */
  4829.     shape->wlines = get2(&loc);                /* lines high */
  4830.     shape->wchars = get2(&loc);                /* chars wide */
  4831.     shape->wfont = get1(&loc);                /* font size */
  4832.     shape->wattr = get2(&loc);                /* attributes */
  4833.  
  4834.     DO DEBUG("ParseShape(): origv %d, origh %d, lines %d, chars %d\n",
  4835.                 shape->worigv, shape->worigh, shape->wlines, shape->wchars);
  4836.     DO DEBUG("   font %d, attr 0x%x, badconv %d\n",
  4837.                     shape->wfont, shape->wattr, Badconvert);
  4838.  
  4839.     return ( Badconvert ? -1 : 0 );            /* return conversion code */
  4840.  
  4841. } /* parseshape() */
  4842.  
  4843.  
  4844.                     /* get4() - convert ASCII to parameter */
  4845.  
  4846. static unsigned
  4847. get4(loc)
  4848. char        **loc;                            /* pointer to fill area pointer */
  4849. {
  4850.     unsigned    hi;                            /* high portion */
  4851.     unsigned    low;                        /* low portion */
  4852.  
  4853.     hi = get2(loc);                            /* get high byte */
  4854.     low = get2(loc);                        /* get low byte */
  4855.  
  4856.     return ( (hi<<8) + low );                /* return word value */
  4857.  
  4858. } /* get4() */
  4859.  
  4860.  
  4861.                     /* get2() - convert ASCII to parameter */
  4862.  
  4863. static unsigned
  4864. get2(loc)
  4865. char        **loc;                            /* pointer to fill area pointer */
  4866. {
  4867.     unsigned    hi;                            /* high portion */
  4868.     unsigned    low;                        /* low portion */
  4869.  
  4870.     hi = get1(loc);                            /* get high half */
  4871.     low = get1(loc);                        /* get low half */
  4872.  
  4873.     return ( (hi<<4) + low );                /* return byte value */
  4874.     
  4875. } /* get2() */
  4876.  
  4877.  
  4878.                     /* get1() - convert ASCII to parameter */
  4879.  
  4880. /*    This function sets 'Badconvert' if an invalid character is detected */
  4881.  
  4882. static unsigned
  4883. get1(loc)
  4884. char        **loc;                            /* pointer to fill area pointer */
  4885. {
  4886.     int            c;                            /* character to convert */
  4887.     
  4888.     c = *(*loc)++;                            /* fetch character */
  4889.     
  4890.     if (c >= '0' && c <= '9')
  4891.         /* zero through nine */
  4892.         return ( c - '0' );                    /* return it's binary value */
  4893.     
  4894.     if (c >= 'a' && c <= 'f')
  4895.         /* lower case hex */
  4896.         return ( c - 'a' + 10);                /* return it's binary value */
  4897.         
  4898.     if (c >= 'A' && c <= 'F')
  4899.         /* upper case hex */
  4900.         return ( c - 'A' + 10);                /* return it's binary value */
  4901.         
  4902.     /* invalid digit! */
  4903.     Badconvert++;                            /* set bad character flag */
  4904.     return ( 0 );                            /* return a zero */
  4905.  
  4906. } /* get1() */
  4907.  
  4908.  
  4909.                     /* myscanf() - RAW mode scanf routine */
  4910.  
  4911. /**    This routine is required because once our terminal is set into RAW mode
  4912. ***    the standard scanf routine fails on 7-bit lines whenever a high bit
  4913. ***    occurs in an input character. Only the %d, %c and exact input character
  4914. ***    images are supported in the input format string. All value parameters 
  4915. *** must be integer data type for both %d and %c.
  4916. */
  4917.  
  4918. static int
  4919. myscanf(str, arg1, arg2, arg3)
  4920. unsigned char    *str;                    /* scanf input string */
  4921. int        *arg1,*arg2,*arg3;                /* integer input pointer arguments */
  4922. {
  4923.     int        numscan = 0;                /* items filled in */
  4924.     int        build;                        /* %d build integer value */
  4925.     int        c;                            /* integer input character */
  4926.  
  4927.     DO dumptime();
  4928.     DO DEBUG("myscanf(%s)\n", str);
  4929.  
  4930.     /* scan string processing formats */
  4931.     while (*str)
  4932.           switch (*str)
  4933.         { case EOF:
  4934.             /* Error: probably our alarm timed out */
  4935.             return ( numscan );
  4936.             /* NOT REACHED */
  4937.  
  4938.           case '%':
  4939.             /* format specifier */
  4940.             switch (*++str)
  4941.             { case 'c':
  4942.                 /* return next character as is */
  4943.                 if ((build=mygetchar()) == -1)
  4944.                     return ( numscan );    /* no input, return count */
  4945.                 break;
  4946.  
  4947.               case 'd':
  4948.                 /* build input decimal value */
  4949.                 build = 0;
  4950.                 while ((c=mygetchar()) >= '0' && c <= '9')
  4951.                   {    build = build * 10;        /* next base ten digit */
  4952.                     build += c - '0';        /* add this digit */
  4953.                   }
  4954.                 myungetc(c);                /* return character ending number */
  4955.                 break;
  4956.  
  4957.           default:
  4958.                 return ( numscan );        /* return if error */
  4959.                 /* NOT REACHED */
  4960.             }
  4961.  
  4962.             /* return value to correct input parameter */
  4963.             switch (numscan)
  4964.             { case 0:
  4965.                 *arg1 = build;
  4966.                 break;
  4967.  
  4968.               case 1:
  4969.                 *arg2 = build;
  4970.                 break;
  4971.  
  4972.               case 2:
  4973.                 *arg3 = build;
  4974.                 break;
  4975.  
  4976.               default:
  4977.                 /* SHOULD NOT OCCUR */
  4978.                 return ( numscan );
  4979.                 /* NOT REACHED */
  4980.             }
  4981.  
  4982.             numscan++;                    /* count items scanned */
  4983.             str++;                        /* bump scan string past 'd' */
  4984.             break;                        /* continue scan */
  4985.  
  4986.           default:
  4987.             /* input character must match exactly */
  4988.             c = mygetchar();
  4989.             if (c != *str)
  4990.                 return ( numscan );        /* return - we don't match string */
  4991.             str++;                        /* to next character */
  4992.  
  4993.         } /* end scan string char switch */
  4994.  
  4995.     /* return number of items scanned */
  4996.     return ( numscan );
  4997.  
  4998. } /* myscanf() */
  4999.  
  5000.  
  5001.             /* mygetchar() - get character stripped to 7 bits */
  5002.  
  5003. /* Return:  -1 if timeout
  5004. **            char stripped to 7 bits
  5005. */
  5006.  
  5007. static int
  5008. mygetchar()
  5009. {
  5010.     int        c;                            /* next input character */
  5011.     int        result;                        /* read return value */
  5012.  
  5013.     DO dumptime();
  5014.  
  5015.     /* if character still in buffer return it */
  5016.     if (insize > 0)
  5017.       {    insize--;                        /* count down */
  5018.         c = (*inpos++) & 0x7f;            /* fetch next char */
  5019.         DO DEBUG(" 0x%lx '%c' ", c, c);
  5020.         return ( c );                    /* return 7-bit character */
  5021.       }
  5022.  
  5023.     /* attempt to read the buffer */
  5024.     result = GetData();                    /* no timeout (caller may have set) */
  5025.  
  5026.     /* return -1 if timeout */
  5027.     if (result == 0)
  5028.       {    DO DEBUG(" mygetchar ret -1\n");
  5029.         return ( -1 );
  5030.       }
  5031.  
  5032.     return ( mygetchar() );                /* return next character */
  5033.  
  5034. #if 0
  5035.     c = getchar() & 0x7f;                /* insure 7-bit only */
  5036.  
  5037. DO DEBUG(" 0x%lx '%c' ", c, c);
  5038.     return ( c );
  5039. #endif
  5040.  
  5041. } /* mygetchar() */
  5042.  
  5043.  
  5044.                 /* myungetc() - unget a character */
  5045.  
  5046. /* Must only be called to return when a character was previously fetched */
  5047.  
  5048. static void
  5049. myungetc(c)
  5050. int        c;                                /* character to unget */
  5051. {
  5052.     DO dumptime();
  5053.     DO DEBUG("myungetc(x%lx/%c)\n", c, c);
  5054.  
  5055.     insize++;                            /* count back up by one */
  5056.     *--inpos = c;                        /* restore previous character */
  5057.  
  5058. } /* myungetc() */
  5059.  
  5060.  
  5061.                 /* myalarm() - setup alarm timeout for next read */
  5062.  
  5063. static int
  5064. myalarm(time)
  5065. int            time;                        /* time in seconds (or zero) */
  5066. {
  5067.     DO dumptime();
  5068.     DO DEBUG("myalarm(%d)\n", time);
  5069.     settimeout = time;                    /* set for next read */
  5070.  
  5071. } /* myalarm() */
  5072.  
  5073.                 /* dumptime() - print out time in seconds */
  5074.  
  5075. /* THIS MAY BE SYSTEM DEPENDENT SO IS BASED UPON DEBUG IFDEF */
  5076. #ifdef DUMPALL
  5077. #include <sys/types.h>
  5078. #include <sys/time.h>
  5079. #endif
  5080.  
  5081. static void
  5082. dumptime()
  5083. {
  5084. #ifdef DUMPALL
  5085.     time_t    seconds;
  5086.     static time_t    base;
  5087.  
  5088.     if (base == 0)
  5089.       {    seconds = 0;
  5090.         base = time(NULL);
  5091.       }
  5092.     else
  5093.         seconds = time(NULL) - base;
  5094.  
  5095.     DO DEBUG("[%3d] ", seconds);
  5096.     
  5097. #endif
  5098. } /* dumptime() */
  5099. @//E*O*F layers_1.10/protocol.c//
  5100. chmod u=rw,g=r,o=r layers_1.10/protocol.c
  5101.  
  5102. echo Inspecting for damage in transit...
  5103. temp=/tmp/shar$$; dtemp=/tmp/.shar$$
  5104. trap "rm -f $temp $dtemp; exit" 0 1 2 3 15
  5105. cat > $temp <<\!!!
  5106.       38     198    1488 INFO
  5107.       76     318    2408 README
  5108.      123     795    4858 layers.1
  5109.     2279    8911   59804 layers.c
  5110.       69     343    2282 layers.h
  5111.      146     589    3586 layersize.c
  5112.       41     176    1242 layertitle.c
  5113.      122     506    2849 macbput.1
  5114.      598    1696   11595 macbput.c
  5115.       85     520    3151 macbput.h
  5116.       95     437    3077 makefile
  5117.     1351    6047   36857 protocol.c
  5118.     5023   20536  133197 total
  5119. !!!
  5120. wc  layers_1.10/INFO layers_1.10/README layers_1.10/layers.1 layers_1.10/layers.c layers_1.10/layers.h layers_1.10/layersize.c layers_1.10/layertitle.c layers_1.10/macbput.1 layers_1.10/macbput.c layers_1.10/macbput.h layers_1.10/makefile layers_1.10/protocol.c | sed 's=[^ ]*/==' | diff -b $temp - >$dtemp
  5121. if [ -s $dtemp ]
  5122. then echo "Ouch [diff of wc output]:" ; cat $dtemp
  5123. else echo "No problems found."
  5124. fi
  5125. exit 0
  5126.  
  5127.  
  5128.